List of usage examples for org.apache.http.client.methods HttpUriRequest getURI
URI getURI();
From source file:com.mutu.gpstracker.breadcrumbs.GetBreadcrumbsTracksTask.java
/** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token./*from ww w. java 2 s . c om*/ */ @Override protected Void doInBackground(Void... params) { mTracks = new LinkedList<Object[]>(); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet( "http://api.gobreadcrumbs.com/v1/bundles/" + mBundleId + "/tracks.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "Execute request: " + request.getURI()); for (Header header : request.getAllHeaders()) { Log.d(TAG, " with header: " + header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if (BreadcrumbsAdapter.DEBUG) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String trackName = null, description = null, difficulty = null, startTime = null, endTime = null, trackRating = null, isPublic = null; Integer trackId = null, bundleId = null, totalTime = null; Float lat = null, lng = null, totalDistance = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("track".equals(xpp.getName()) && trackId != null && bundleId != null) { mTracks.add(new Object[] { trackId, trackName, bundleId, description, difficulty, startTime, endTime, isPublic, lat, lng, totalDistance, totalTime, trackRating }); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("bundle-id".equals(tagName)) { bundleId = Integer.parseInt(xpp.getText()); } else if ("description".equals(tagName)) { description = xpp.getText(); } else if ("difficulty".equals(tagName)) { difficulty = xpp.getText(); } else if ("start-time".equals(tagName)) { startTime = xpp.getText(); } else if ("end-time".equals(tagName)) { endTime = xpp.getText(); } else if ("id".equals(tagName)) { trackId = Integer.parseInt(xpp.getText()); } else if ("is-public".equals(tagName)) { isPublic = xpp.getText(); } else if ("lat".equals(tagName)) { lat = Float.parseFloat(xpp.getText()); } else if ("lng".equals(tagName)) { lng = Float.parseFloat(xpp.getText()); } else if ("name".equals(tagName)) { trackName = xpp.getText(); } else if ("track-rating".equals(tagName)) { trackRating = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "A problem while reading the XML data"); } finally { if (responseEntity != null) { try { //EntityUtils.consume(responseEntity); responseEntity.consumeContent(); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } return null; }
From source file:mobi.dlys.android.core.net.http.handler.AsyncHttpResponseHandler.java
public void sendResponseMessage(HttpResponse response, HttpUriRequest request) { StatusLine status = response.getStatusLine(); String responseBody = null;/*from w w w . j a v a 2s .c o m*/ BufferedInputStream in = null; int responseCode = status.getStatusCode(); if (200 != responseCode) { try { printRequest(request.getURI().toString(), "", EntityUtils.toString(response.getEntity())); } catch (Exception e) { } HttpResponseException exception = new HttpResponseException(status.getStatusCode(), status.getStatusCode() + " " + status.getReasonPhrase()); sendFailureMessage(exception, responseBody); return; } long length = 0; Header[] headers = response.getAllHeaders(); Header[] contentLength = response.getHeaders("Content-Length"); if (null != contentLength && contentLength.length > 0) { String c = contentLength[0].getName(); String v = contentLength[0].getValue(); if (v != null) { v = v.trim(); try { length = Integer.parseInt(v); } catch (NumberFormatException e) { length = 0; } } } // LogUtils.log(TAG, "response code:" + responseCode + // " response content length:" + length); HttpEntity temp = response.getEntity(); if (null != temp) { try { in = new BufferedInputStream(temp.getContent()); // if (length > 0) { int len = -1; byte[] b = new byte[1024]; StringBuffer sb = new StringBuffer(); while ((len = in.read(b)) != -1) { String str = new String(b, 0, len); sb.append(str); } responseBody = sb.toString(); printRequest(request.getURI().toString(), "", responseBody); // } } catch (IOException e) { printRequest(request.getURI().toString(), "", e.getMessage()); sendFailureMessage(e, (String) null); return; } finally { try { if (null != in) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } } sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody); }
From source file:org.codegist.crest.HttpClientRestService.java
public HttpResponse exec(HttpRequest httpRequest) throws HttpException { HttpUriRequest request; try {/* w w w .j av a 2s. com*/ request = toHttpUriRequest(httpRequest); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } org.apache.http.HttpResponse response; HttpEntity entity = null; boolean inError = false; try { logger.debug("%4s %s", httpRequest.getMeth(), request.getURI()); logger.trace(request); response = http.execute(request); if (response == null) { throw new HttpException("No Response!", new HttpResponse(httpRequest, -1)); } entity = response.getEntity(); HttpResponse res; if (entity != null) { res = new HttpResponse(httpRequest, response.getStatusLine().getStatusCode(), toHeaders(response.getAllHeaders()), new HttpResourceImpl(request, entity)); if (res.getStatusCode() != HttpStatus.SC_OK) { throw new HttpException(response.getStatusLine().getReasonPhrase(), res); } } else if (httpRequest.getMeth().equals(HttpMethod.HEAD)) { res = new HttpResponse(httpRequest, response.getStatusLine().getStatusCode(), toHeaders(response.getAllHeaders())); } else { throw new HttpException(response.getStatusLine().getReasonPhrase(), new HttpResponse(httpRequest, response.getStatusLine().getStatusCode(), toHeaders(response.getAllHeaders()))); } logger.trace("HTTP Response %s", response); return res; } catch (HttpException e) { inError = true; throw e; } catch (Throwable e) { inError = true; throw new HttpException(e, new HttpResponse(httpRequest, -1)); } finally { if (inError) { if (entity != null) { try { entity.consumeContent(); } catch (IOException e1) { //ignore } } request.abort(); } } }
From source file:jetbrains.buildServer.commitPublisher.github.api.impl.GitHubApiImpl.java
private void logFailedResponse(@NotNull HttpUriRequest request, @Nullable String requestEntity, @NotNull HttpResponse execute) throws IOException { String responseText = extractResponseEntity(execute); if (responseText == null) { responseText = "<none>"; }//w ww. j a v a2 s. c o m if (requestEntity == null) { requestEntity = "<none>"; } LOG.warn("Failed to complete query to GitHub with:\n" + " requestURL: " + request.getURI().toString() + "\n" + " requestMethod: " + request.getMethod() + "\n" + " requestEntity: " + requestEntity + "\n" + " response: " + execute.getStatusLine() + "\n" + " responseEntity: " + responseText); }
From source file:org.graphity.core.util.jena.HttpOp.java
private static void exec(String url, HttpUriRequest request, String acceptHeader, HttpResponseHandler handler, HttpClient httpClient, HttpContext httpContext, HttpAuthenticator authenticator) { try {//w w w . j a v a 2s .c o m if (handler == null) // This cleans up. handler = nullHandler; long id = counter.incrementAndGet(); String requestURI = determineRequestURI(url); String baseURI = determineBaseIRI(url); if (log.isDebugEnabled()) log.debug(format("[%d] %s %s", id, request.getMethod(), request.getURI().toString())); // Accept if (acceptHeader != null) request.addHeader(HttpNames.hAccept, acceptHeader); // Prepare and execute httpClient = ensureClient(httpClient, authenticator); httpContext = ensureContext(httpContext); applyAuthentication(asAbstractClient(httpClient), url, httpContext, authenticator); HttpResponse response = httpClient.execute(request, httpContext); // Response StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (HttpSC.isClientError(statusCode) || HttpSC.isServerError(statusCode)) { log.debug(format("[%d] %s %s", id, statusLine.getStatusCode(), statusLine.getReasonPhrase())); // Error responses can have bodies so it is important to clear up. EntityUtils.consume(response.getEntity()); throw new HttpException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } // Redirects are followed by HttpClient. if (handler != null) handler.handle(baseURI, response); } catch (IOException ex) { throw new HttpException(ex); } }
From source file:tech.sirwellington.alchemy.http.HttpVerbImpl.java
@Override public HttpResponse execute(HttpClient apacheHttpClient, HttpRequest request) throws AlchemyHttpException { checkThat(apacheHttpClient, request).usingMessage("null arguments").are(notNull()); HttpUriRequest apacheRequest = requestMapper.convertToApacheRequest(request); checkThat(apacheRequest).throwing(ex -> new AlchemyHttpException("Could not map HttpRequest: " + request)) .is(notNull());/*from w w w. j ava 2 s. c om*/ request.getRequestHeaders().forEach(apacheRequest::addHeader); org.apache.http.HttpResponse apacheResponse; try { apacheResponse = apacheHttpClient.execute(apacheRequest); } catch (Exception ex) { LOG.error("Failed to execute GET Request on {}", apacheRequest.getURI(), ex); throw new AlchemyHttpException(ex); } checkThat(apacheResponse) .throwing(ex -> new AlchemyHttpException(request, "Missing Apache Client Response")).is(notNull()); JsonElement json; try { json = extractJsonFromResponse(request, apacheResponse); } catch (JsonParseException ex) { LOG.error("Could not parse Response from Request {} as JSON", request, ex); throw new JsonException(request, "Failed to parse Json", ex); } catch (Exception ex) { LOG.error("Could not parse Response from Request {}", request, ex); throw new OperationFailedException(request, ex); } finally { if (apacheResponse instanceof CloseableHttpResponse) { try { ((CloseableHttpResponse) apacheResponse).close(); } catch (IOException ex) { LOG.error("Failed to close HTTP Response.", ex); throw new OperationFailedException(request, "Could not close Http Response"); } } } HttpResponse response = HttpResponse.Builder.newInstance().withResponseBody(json) .withStatusCode(apacheResponse.getStatusLine().getStatusCode()) .withResponseHeaders(extractHeadersFrom(apacheResponse)).usingGson(gson).build(); return response; }
From source file:com.asakusafw.yaess.jobqueue.client.HttpJobClient.java
private JobStatus extractJobStatus(HttpUriRequest request, HttpResponse response) throws IOException { assert request != null; assert response != null; JobStatus status = extractContent(JobStatus.class, request, response); if (status.getKind() == null) { throw new IOException(MessageFormat.format("status was not specified: {0}", request.getURI())); }/* w w w. ja v a 2s . com*/ if (status.getKind() != JobStatus.Kind.ERROR && status.getJobId() == null) { throw new IOException(MessageFormat.format("job request ID was not specified: {0}", request.getURI())); } if (status.getKind() == JobStatus.Kind.COMPLETED && status.getExitCode() == null) { throw new IOException(MessageFormat.format("exit code was not specified: {0}", request.getURI())); } return status; }
From source file:org.elasticsearch.client.RestClientSingleHostTests.java
@Before @SuppressWarnings("unchecked") public void createRestClient() throws IOException { httpClient = mock(CloseableHttpAsyncClient.class); when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))) .thenAnswer(new Answer<Future<HttpResponse>>() { @Override public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable { HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock .getArguments()[0]; HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2]; assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class)); FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock .getArguments()[3]; HttpUriRequest request = (HttpUriRequest) requestProducer.generateRequest(); //return the desired status code or exception depending on the path if (request.getURI().getPath().equals("/soe")) { futureCallback.failed(new SocketTimeoutException()); } else if (request.getURI().getPath().equals("/coe")) { futureCallback.failed(new ConnectTimeoutException()); } else { int statusCode = Integer.parseInt(request.getURI().getPath().substring(1)); StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, ""); HttpResponse httpResponse = new BasicHttpResponse(statusLine); //return the same body that was sent if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { assertTrue( "the entity is not repeatable, cannot set it to the response directly", entity.isRepeatable()); httpResponse.setEntity(entity); }/*from ww w.jav a 2s . co m*/ } //return the same headers that were sent httpResponse.setHeaders(request.getAllHeaders()); futureCallback.completed(httpResponse); } return null; } }); defaultHeaders = RestClientTestUtil.randomHeaders(getRandom(), "Header-default"); httpHost = new HttpHost("localhost", 9200); failureListener = new HostsTrackingFailureListener(); restClient = new RestClient(httpClient, 10000, defaultHeaders, new HttpHost[] { httpHost }, null, failureListener); }
From source file:net.fischboeck.discogs.BaseOperations.java
CloseableHttpResponse doHttpRequest(HttpUriRequest request) throws EntityNotFoundException, ClientException { CloseableHttpResponse response = null; request = this.authorizationStrategy.authorize(request); try {//from w ww . ja va 2 s . c o m response = this.httpClient.execute(request); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { response.close(); throw new EntityNotFoundException("API returned 404 on request GET " + request.getURI()); } return response; } catch (EntityNotFoundException enfEx) { throw enfEx; } catch (Exception ex) { throw new ClientException(ex.getMessage()); } }