List of usage examples for org.apache.http.client.methods HttpUriRequest getRequestLine
RequestLine getRequestLine();
From source file:com.goliathonline.android.kegbot.io.RemoteExecutor.java
/** * Execute this {@link HttpUriRequest}, passing a valid response through * {@link JsonHandler#parseAndApply(JSONObject, ContentResolver)}. *//* w w w . j av a2s.co m*/ public void execute(HttpUriRequest request, JsonHandler handler) throws HandlerException { try { final HttpResponse resp = mHttpClient.execute(request); final int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK && status != HttpStatus.SC_NOT_FOUND) { throw new HandlerException( "Unexpected server response " + resp.getStatusLine() + " for " + request.getRequestLine()); } final InputStream input = resp.getEntity().getContent(); try { final String inString = ParserUtils.convertStreamToString(input); final JSONObject parser = new JSONObject(inString); handler.parseAndApply(parser, mResolver); } catch (JSONException e) { throw new HandlerException("Malformed response for " + request.getRequestLine(), e); } finally { if (input != null) input.close(); } } catch (HandlerException e) { throw e; } catch (IOException e) { throw new HandlerException("Problem reading remote response for " + request.getRequestLine(), e); } }
From source file:org.xbmc.android.jsonrpc.io.RemoteExecutor.java
/** * Execute this {@link HttpUriRequest}, passing a valid response through * {@link JsonHandler#parseAndApply(XmlPullParser, ContentResolver)}. *///from www . j ava 2s .c o m public void execute(HttpUriRequest request, JsonHandler handler) throws HandlerException { try { final HttpResponse resp = mHttpClient.execute(request); final int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { throw new HandlerException( "Unexpected server response " + resp.getStatusLine() + " for " + request.getRequestLine()); } final InputStream input = resp.getEntity().getContent(); try { final BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"), 8192); final StringBuilder sb = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { sb.append(line).append("\n"); } //Log.d(TAG, "RESPONSE: " + sb.toString()); handler.parseAndApply(sb, mResolver); } catch (HandlerException e) { throw e; } finally { if (input != null) input.close(); } } catch (HandlerException e) { throw e; } catch (IOException e) { throw new HandlerException("Problem reading remote response for " + request.getRequestLine(), e); } }
From source file:net.peterkuterna.android.apps.devoxxsched.io.RemoteExecutor.java
/** * Execute this {@link HttpUriRequest}, passing a valid response through * {@link JSONHandler#parseAndApply(JSONArray, ContentResolver)}. *///from w w w. j av a 2s . c o m public JSONArray executeRequest(HttpUriRequest request) throws JSONHandlerException { try { final HttpResponse resp = mHttpClient.execute(request); final int status = resp.getStatusLine().getStatusCode(); Log.d("RemoteExecutor", "status = " + status); if (status != HttpStatus.SC_OK) { throw new JSONHandlerException( "Unexpected server response " + resp.getStatusLine() + " for " + request.getRequestLine()); } final InputStream input = resp.getEntity().getContent(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(input)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } String jsontext = sb.toString(); return new JSONArray(jsontext); } catch (JSONException e) { throw new JSONHandlerException("Malformed response for " + request.getRequestLine(), e); } finally { if (input != null) input.close(); } } catch (JSONHandlerException e) { throw e; } catch (IOException e) { throw new JSONHandlerException("Problem reading remote response for " + request.getRequestLine(), e); } }
From source file:com.siddroid.offlinews.SendOffline.java
/** * Fetch response./*from ww w .j a v a 2s . c om*/ * This function executes request. * @param request the request * @param client the client * @return the input stream */ private InputStream fetchResponse(HttpUriRequest request, DefaultHttpClient client) { try { Log.d("CHECK", ("executing request " + request.getRequestLine())); /*execute request and get response*/ HttpResponse getResponse = client.execute(request); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.d(getClass().getSimpleName(), "Error " + statusCode + " for URL " + request.getURI()); return null; } HttpEntity getResponseEntity = getResponse.getEntity(); /*return response inputstream*/ return getResponseEntity.getContent(); } catch (IOException e) { request.abort(); } return null; }
From source file:org.dataconservancy.access.connector.HttpDcsConnector.java
/** * Execute the supplied request. Method is package-private for unit testing. * * @param req the request object/*from www. j a v a 2s. com*/ * @param success_status http response status needed for the execution to succeed * @return an HttpResponse * @throws DcsClientFault if the response status code is between 400 to 499 inclusive * @throws DcsServerException if the response status code is 500 or greater * @throws HttpIoException if a connection cannot be obtained from the connection pool, or an I/O error occurs * @throws DcsConnectorRuntimeException if any other RuntimeExceptions are caught */ HttpResponse execute(HttpUriRequest req, int success_status) throws DcsClientFault { HttpResponse response = null; String requestUri = null; try { requestUri = req.getRequestLine().getUri(); response = client.execute(req); } catch (ConnectionPoolTimeoutException e) { throw new HttpIoException( "Timeout reached while obtaining an HTTP connection from the connection pool. " + "First, ensure response InputStreams are being read (this frees the connection), then try to " + "increase the maximum number of connections, or increase the connection pool timeout.", e); } catch (IOException e) { throw new HttpIoException("Could not retrieve " + requestUri + ": " + e.getMessage(), e); } catch (IllegalStateException e) { // thrown when trying to re-use a connection that hasn't been closed req.abort(); throw new DcsClientFault(e.getMessage(), e); } catch (RuntimeException e) { req.abort(); throw new DcsConnectorRuntimeException(e.getMessage(), e); } final int statusCode = response.getStatusLine().getStatusCode(); final String statusReason = response.getStatusLine().getReasonPhrase(); if (statusCode != success_status) { req.abort(); if (statusCode >= 400 && statusCode < 500) { throw new DcsClientFault("Could not retrieve " + requestUri + ": response from server was " + statusCode + " '" + statusReason + "'"); } if (statusCode >= 500) { throw new DcsServerException("Could not retrieve " + requestUri + ": response from server was " + statusCode + " '" + statusReason + "'"); } if (statusCode > 200 && statusCode < 300) { log.debug("Received status {} for {}", statusCode, requestUri); // TODO } if (statusCode >= 300 && statusCode < 400) { log.debug("Received status {} for {}", statusCode, requestUri); // TODO } if (statusCode >= 100 && statusCode < 200) { log.debug("Received status {} for {}", statusCode, requestUri); // TODO } } return response; }
From source file:org.francho.apps.zgzpolen.service.PollenService.java
/** * Execute this {@link HttpUriRequest}, passing a valid response and save it in the database */* ww w .ja v a2 s . c om*/ * @param request * @throws PollenServiceException */ public void execute(HttpUriRequest request) throws PollenServiceException { try { final HttpResponse resp = HttpHelper.getHttpClient(this).execute(request); final int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { throw new PollenServiceException( "Unexpected server response " + resp.getStatusLine() + " for " + request.getRequestLine()); } final InputStream input = resp.getEntity().getContent(); try { final XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); parser.setInput(input, null); ZgzPollenXmlParser pollenParser = new ZgzPollenXmlParser(); final ArrayList<ContentProviderOperation> operations = pollenParser.parse(parser); getContentResolver().applyBatch(PollenContract.CONTENT_AUTHORITY, operations); setPollenDate(pollenParser.getPolenDate()); } catch (XmlPullParserException e) { throw new PollenServiceException("Malformed response for " + request.getRequestLine(), e); } catch (RemoteException e) { throw new PollenServiceException("Problem parsing response for " + request.getRequestLine(), e); } catch (OperationApplicationException e) { throw new PollenServiceException("Problem saving response for " + request.getRequestLine(), e); } finally { if (input != null) input.close(); } } catch (PollenServiceException e) { throw e; } catch (IOException e) { throw new PollenServiceException("Problem reading remote response for " + request.getRequestLine(), e); } }
From source file:org.duniter.core.client.service.HttpServiceImpl.java
protected boolean executeRequest(HttpClient httpClient, HttpUriRequest request) { if (log.isDebugEnabled()) { log.debug("Executing request : " + request.getRequestLine()); }/*from w w w . ja v a2 s. c o m*/ try { HttpResponse response = httpClient.execute(request); switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: { response.getEntity().consumeContent(); return true; } case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_FORBIDDEN: throw new TechnicalException(I18n.t("duniter4j.client.authentication")); default: throw new TechnicalException( I18n.t("duniter4j.client.status", response.getStatusLine().toString())); } } catch (ConnectException e) { throw new TechnicalException(I18n.t("duniter4j.client.core.connect"), e); } catch (IOException e) { throw new TechnicalException(e.getMessage(), e); } }
From source file:com.android.exchange.service.EasServerConnection.java
/** * Executes an {@link HttpUriRequest}.//from ww w.j a v a 2s . com * Note: this function must not be called by multiple threads concurrently. Only one thread may * send server requests from a particular object at a time. * @param method The post to execute. * @param timeout The timeout to use. * @return The response from the Exchange server. * @throws IOException */ public EasResponse executeHttpUriRequest(final HttpUriRequest method, final long timeout) throws IOException, CertificateException { LogUtils.d(TAG, "EasServerConnection about to make request %s", method.getRequestLine()); // The synchronized blocks are here to support the stop() function, specifically to handle // when stop() is called first. Notably, they are NOT here in order to guard against // concurrent access to this function, which is not supported. synchronized (this) { if (mStopped) { mStopped = false; // If this gets stopped after the POST actually starts, it throws an IOException. // Therefore if we get stopped here, let's throw the same sort of exception, so // callers can equate IOException with "this POST got killed for some reason". throw new IOException("Command was stopped before POST"); } mPendingRequest = method; } boolean postCompleted = false; try { final EasResponse response = EasResponse.fromHttpRequest(getClientConnectionManager(), getHttpClient(timeout), method); postCompleted = true; return response; } finally { synchronized (this) { mPendingRequest = null; if (postCompleted) { mStoppedReason = STOPPED_REASON_NONE; } } } }
From source file:org.duniter.core.client.service.HttpServiceImpl.java
protected <T> T executeRequest(HttpClient httpClient, HttpUriRequest request, Class<? extends T> resultClass, Class<?> errorClass, int retryCount) { T result = null;/*from www .j ava 2 s. c om*/ if (debug) { log.debug("Executing request : " + request.getRequestLine()); } boolean retry = false; HttpResponse response = null; try { response = httpClient.execute(request); if (debug) { log.debug("Received response : " + response.getStatusLine()); } switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: { if (resultClass == null || resultClass.equals(HttpResponse.class)) { result = (T) response; } else { result = (T) parseResponse(request, response, resultClass); EntityUtils.consume(response.getEntity()); } break; } case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_FORBIDDEN: throw new HttpUnauthorizeException(I18n.t("duniter4j.client.authentication")); case HttpStatus.SC_NOT_FOUND: throw new HttpNotFoundException(I18n.t("duniter4j.client.notFound", request.toString())); case HttpStatus.SC_BAD_REQUEST: try { Object errorResponse = parseResponse(request, response, errorClass); if (errorResponse instanceof Error) { throw new HttpBadRequestException((Error) errorResponse); } else { throw new HttpBadRequestException(errorResponse.toString()); } } catch (IOException e) { throw new HttpBadRequestException( I18n.t("duniter4j.client.status", response.getStatusLine().toString())); } case HttpStatus.SC_SERVICE_UNAVAILABLE: case Constants.HttpStatus.SC_TOO_MANY_REQUESTS: retry = true; break; default: String defaultMessage = I18n.t("duniter4j.client.status", request.toString(), response.getStatusLine().toString()); if (isContentType(response, ContentType.APPLICATION_JSON)) { JsonNode node = objectMapper.readTree(response.getEntity().getContent()); if (node.hasNonNull("ucode")) { throw new BmaTechnicalException(node.get("ucode").asInt(), node.get("message").asText(defaultMessage)); } } throw new TechnicalException(defaultMessage); } } catch (ConnectException e) { throw new HttpConnectException(I18n.t("duniter4j.client.core.connect", request.toString()), e); } catch (SocketTimeoutException | ConnectTimeoutException e) { throw new HttpTimeoutException(I18n.t("duniter4j.client.core.timeout"), e); } catch (TechnicalException e) { throw e; } catch (Throwable e) { throw new TechnicalException(e.getMessage(), e); } finally { // Close is need if (response instanceof CloseableHttpResponse) { try { ((CloseableHttpResponse) response).close(); } catch (IOException e) { // Silent is gold } } } // HTTP requests limit exceed, retry when possible if (retry) { if (retryCount > 0) { log.debug(String.format("Service unavailable: waiting [%s ms] before retrying...", Constants.Config.TOO_MANY_REQUEST_RETRY_TIME)); try { Thread.sleep(Constants.Config.TOO_MANY_REQUEST_RETRY_TIME); } catch (InterruptedException e) { throw new TechnicalException(I18n.t("duniter4j.client.status", request.toString(), response.getStatusLine().toString())); } // iterate return executeRequest(httpClient, request, resultClass, errorClass, retryCount - 1); } else { throw new TechnicalException( I18n.t("duniter4j.client.status", request.toString(), response.getStatusLine().toString())); } } return result; }
From source file:com.loganlinn.pivotaltrackie.io.RemoteExecutor.java
/** * Execute this {@link HttpUriRequest}, passing a valid response through * {@link XmlHandler#parseAndApply(XmlPullParser, ContentResolver)}. * @throws ResponseException //from w w w.j a v a2s .c om */ public void execute(HttpUriRequest request, XmlHandler handler) throws HandlerException { Log.i(TAG, "Executing Remote " + request.getMethod() + " Request: " + request.getURI()); try { // Execute the HttpRequest final HttpResponse resp = mHttpClient.execute(request); final int status = resp.getStatusLine().getStatusCode(); Log.i(TAG, "Request Response: " + status); final boolean notFound = (status != HttpStatus.SC_NOT_FOUND); if (status != HttpStatus.SC_OK && !notFound) { throw new HandlerException( "Unexpected server response " + resp.getStatusLine() + " for " + request.getRequestLine()); } if (notFound) { final InputStream input = resp.getEntity().getContent(); // Parse the input stream using the handler try { final XmlPullParser parser = ParserUtils.newPullParser(input); handler.parseAndApply(parser, mResolver); } catch (XmlPullParserException e) { throw new HandlerException("Malformed response for " + request.getRequestLine(), e); } finally { if (input != null) input.close(); } } else if (handler.getContentUri() != null) { Log.i(TAG, "Deleting " + handler.getContentUri().toString()); mResolver.delete(handler.getContentUri(), null, null); } } catch (HandlerException e) { throw e; } catch (IOException e) { throw new HandlerException("Problem reading remote response for " + request.getRequestLine(), e); } }