List of usage examples for org.apache.http.client.methods HttpUriRequest getURI
URI getURI();
From source file:org.apache.sling.testing.clients.AbstractSlingClient.java
/** * <p>Executes an HTTP request, WITHOUT consuming the entity in the response. The caller is responsible for consuming the entity or * closing the response's InputStream in order to release the connection. * Otherwise, the client might run out of connections and will block</p> * * <p><b>Use this with caution and only if necessary for streaming</b>, otherwise use the safe method * {@link #doRequest(HttpUriRequest, List, int...)}</p> * * <p>Adds the headers and checks the response against expected status</p> * * @param request the request to be executed * @param headers optional headers to be added to the request * @param expectedStatus if passed, the response status is checked against it/them, and has to match at least one of them * @return the response, with the entity not consumed * @throws ClientException if the request could not be executed *///from ww w . ja va2 s. c om public SlingHttpResponse doStreamRequest(HttpUriRequest request, List<Header> headers, int... expectedStatus) throws ClientException { // create context from config HttpClientContext context = createHttpClientContextFromConfig(); // add headers if (headers != null) { request.setHeaders(headers.toArray(new Header[headers.size()])); } try { log.debug("request {} {}", request.getMethod(), request.getURI()); SlingHttpResponse response = new SlingHttpResponse(this.execute(request, context)); log.debug("response {}", HttpUtils.getHttpStatus(response)); // Check the status and throw a ClientException if it doesn't match expectedStatus, but close the entity before if (expectedStatus != null && expectedStatus.length > 0) { try { HttpUtils.verifyHttpStatus(response, expectedStatus); } catch (ClientException e) { // catch the exception to make sure we close the entity before re-throwing it response.close(); throw e; } } return response; } catch (IOException e) { throw new ClientException("Could not execute http request", e); } }
From source file:com.keydap.sparrow.SparrowClient.java
private <T> SearchResponse<T> sendSearchRequest(HttpUriRequest req, Class<T> resClas) { SearchResponse<T> result = new SearchResponse<T>(); try {/*from w w w .jav a2s .c o m*/ LOG.debug("Sending {} request to {}", req.getMethod(), req.getURI()); authenticator.addHeaders(req); HttpResponse resp = client.execute(req); authenticator.saveHeaders(resp); StatusLine sl = resp.getStatusLine(); int code = sl.getStatusCode(); LOG.debug("Received status code {} from the request to {}", code, req.getURI()); HttpEntity entity = resp.getEntity(); String json = null; if (entity != null) { json = EntityUtils.toString(entity); } result.setHttpBody(json); result.setHttpCode(code); result.setHeaders(resp.getAllHeaders()); // if it is success there will be response body to read if (code == 200) { if (json != null) { // DELETE will have no response body, so check for null JsonObject obj = (JsonObject) new JsonParser().parse(json); JsonElement je = obj.get("totalResults"); if (je != null) { result.setTotalResults(je.getAsInt()); } je = obj.get("startIndex"); if (je != null) { result.setStartIndex(je.getAsInt()); } je = obj.get("itemsPerPage"); if (je != null) { result.setItemsPerPage(je.getAsInt()); } je = obj.get("Resources"); // yes, the 'R' in resources must be upper case if (je != null) { JsonArray arr = je.getAsJsonArray(); Iterator<JsonElement> itr = arr.iterator(); List<T> resources = new ArrayList<T>(); while (itr.hasNext()) { JsonObject r = (JsonObject) itr.next(); if (resClas != null) { resources.add(unmarshal(r, resClas)); } else { T rsObj = unmarshal(r); if (rsObj == null) { LOG.warn( "No resgistered resource class found to deserialize the resource data {}", r); } else { resources.add(rsObj); } } } if (!resources.isEmpty()) { result.setResources(resources); } } } } else { if (json != null) { Error error = serializer.fromJson(json, Error.class); result.setError(error); } } } catch (Exception e) { e.printStackTrace(); LOG.warn("", e); result.setHttpCode(-1); Error err = new Error(); err.setDetail(e.getMessage()); result.setError(err); } return result; }
From source file:github.madmarty.madsonic.service.RESTMusicService.java
private void detectRedirect(String originalUrl, Context context, HttpContext httpContext) { HttpUriRequest request = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // Sometimes the request doesn't contain the "http://host" part String redirectedUrl;/*from www .j a v a2 s . c om*/ if (request.getURI().getScheme() == null) { redirectedUrl = host.toURI() + request.getURI(); } else { redirectedUrl = request.getURI().toString(); } redirectFrom = originalUrl.substring(0, originalUrl.indexOf("/rest/")); redirectTo = redirectedUrl.substring(0, redirectedUrl.indexOf("/rest/")); Log.i(TAG, redirectFrom + " redirects to " + redirectTo); redirectionLastChecked = System.currentTimeMillis(); redirectionNetworkType = getCurrentNetworkType(context); }
From source file:vn.mbm.phimp.me.gallery3d.picasa.GDataClient.java
private void callMethod(HttpUriRequest request, Operation operation) throws IOException { // Specify GData protocol version 2.0. request.addHeader("GData-Version", "2"); // Indicate support for gzip-compressed responses. request.addHeader("Accept-Encoding", "gzip"); // Specify authorization token if provided. String authToken = mAuthToken; if (!TextUtils.isEmpty(authToken)) { request.addHeader("Authorization", "GoogleLogin auth=" + authToken); }/* ww w. j a va2 s .c o m*/ // Specify the ETag of a prior response, if available. String etag = operation.inOutEtag; if (etag != null) { request.addHeader("If-None-Match", etag); } // Execute the HTTP request. HttpResponse httpResponse = null; try { httpResponse = mHttpClient.execute(request); } catch (IOException e) { Log.w(TAG, "Request failed: " + request.getURI()); throw e; } // Get the status code and response body. int status = httpResponse.getStatusLine().getStatusCode(); InputStream stream = null; HttpEntity entity = httpResponse.getEntity(); if (entity != null) { // Wrap the entity input stream in a GZIP decoder if necessary. stream = entity.getContent(); if (stream != null) { Header header = entity.getContentEncoding(); if (header != null) { if (header.getValue().contains("gzip")) { stream = new GZIPInputStream(stream); } } } } // Return the stream if successful. Header etagHeader = httpResponse.getFirstHeader("ETag"); operation.outStatus = status; operation.inOutEtag = etagHeader != null ? etagHeader.getValue() : null; operation.outBody = stream; }
From source file:net.yacy.cora.protocol.http.HTTPClient.java
private void storeConnectionInfo(final HttpUriRequest httpUriRequest) { final int port = httpUriRequest.getURI().getPort(); final String thost = httpUriRequest.getURI().getHost(); //assert thost != null : "uri = " + httpUriRequest.getURI().toString(); ConnectionInfo.addConnection(//from w ww . ja v a 2s . c o m new ConnectionInfo(httpUriRequest.getURI().getScheme(), port == -1 ? thost : thost + ":" + port, httpUriRequest.getMethod() + " " + httpUriRequest.getURI().getPath(), httpUriRequest.hashCode(), System.currentTimeMillis(), this.upbytes)); }
From source file:com.ocp.picasa.GDataClient.java
private void callMethod(HttpUriRequest request, Operation operation) throws IOException { // Specify GData protocol version 2.0. request.addHeader("GData-Version", "2"); // Indicate support for gzip-compressed responses. request.addHeader("Accept-Encoding", "gzip"); // Specify authorization token if provided. String authToken = mAuthToken; if (!TextUtils.isEmpty(authToken)) { request.addHeader("Authorization", "GoogleLogin auth=" + authToken); }/*from ww w .jav a 2 s. c o m*/ // Specify the ETag of a prior response, if available. String etag = operation.inOutEtag; if (etag != null) { request.addHeader("If-None-Match", etag); } // Execute the HTTP request. HttpResponse httpResponse = null; try { httpResponse = mHttpClient.execute(request); } catch (IOException e) { Log.w(Gallery.TAG, TAG + ": " + "Request failed: " + request.getURI()); throw e; } // Get the status code and response body. int status = httpResponse.getStatusLine().getStatusCode(); InputStream stream = null; HttpEntity entity = httpResponse.getEntity(); if (entity != null) { // Wrap the entity input stream in a GZIP decoder if necessary. stream = entity.getContent(); if (stream != null) { Header header = entity.getContentEncoding(); if (header != null) { if (header.getValue().contains("gzip")) { stream = new GZIPInputStream(stream); } } } } // Return the stream if successful. Header etagHeader = httpResponse.getFirstHeader("ETag"); operation.outStatus = status; operation.inOutEtag = etagHeader != null ? etagHeader.getValue() : null; operation.outBody = stream; }
From source file:org.keycloak.testsuite.util.SamlClient.java
public <T> T executeAndTransform(ResultExtractor<T> resultTransformer, List<Step> steps) { CloseableHttpResponse currentResponse = null; URI currentUri = URI.create("about:blank"); strategy.setRedirectable(true);//from w ww. ja va2 s. c o m try (CloseableHttpClient client = createHttpClientBuilderInstance().setRedirectStrategy(strategy).build()) { for (int i = 0; i < steps.size(); i++) { Step s = steps.get(i); LOG.infof("Running step %d: %s", i, s.getClass()); CloseableHttpResponse origResponse = currentResponse; HttpUriRequest request = s.perform(client, currentUri, origResponse, context); if (request == null) { LOG.info("Last step returned no request, continuing with next step."); continue; } // Setting of follow redirects has to be set before executing the final request of the current step if (i < steps.size() - 1 && steps.get(i + 1) instanceof DoNotFollowRedirectStep) { LOG.debugf("Disabling following redirects"); strategy.setRedirectable(false); i++; } else { strategy.setRedirectable(true); } LOG.infof("Executing HTTP request to %s", request.getURI()); currentResponse = client.execute(request, context); currentUri = request.getURI(); List<URI> locations = context.getRedirectLocations(); if (locations != null && !locations.isEmpty()) { currentUri = locations.get(locations.size() - 1); } LOG.infof("Landed to %s", currentUri); if (currentResponse != origResponse && origResponse != null) { origResponse.close(); } } LOG.info("Going to extract response"); return resultTransformer.extract(currentResponse); } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:net.sourceforge.kalimbaradio.androidapp.service.RESTMusicService.java
private void detectRedirect(String originalUrl, Context context, HttpContext httpContext) { HttpUriRequest request = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // Sometimes the request doesn't contain the "http://host" part so we // must take from the HttpHost object. String redirectedUrl;//from w w w. j a v a2 s. c o m if (request.getURI().getScheme() == null) { redirectedUrl = host.toURI() + request.getURI(); } else { redirectedUrl = request.getURI().toString(); } redirectFrom = originalUrl.substring(0, originalUrl.indexOf("/rest/")); redirectTo = redirectedUrl.substring(0, redirectedUrl.indexOf("/rest/")); LOG.info(redirectFrom + " redirects to " + redirectTo); redirectionLastChecked = System.currentTimeMillis(); redirectionNetworkType = getCurrentNetworkType(context); }
From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java
/** * Parses the result and fills the SampleResult with its info * @param httpRequest the executed request * @param localContext the Http context which was used * @param res the SampleResult which is to be filled * @param httpResponse the response which is to be parsed * @throws IllegalStateException/*from w ww . j av a 2s . c o m*/ * @throws IOException */ private void parseResponse(HttpRequestBase httpRequest, HttpContext localContext, HTTPSampleResult res, HttpResponse httpResponse) throws IllegalStateException, IOException { // Needs to be done after execute to pick up all the headers final HttpRequest request = (HttpRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); // We've finished with the request, so we can add the LocalAddress to it for display final InetAddress localAddr = (InetAddress) httpRequest.getParams() .getParameter(ConnRoutePNames.LOCAL_ADDRESS); if (localAddr != null) { request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString()); } res.setRequestHeaders(getConnectionHeaders(request)); Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE); if (contentType != null) { String ct = contentType.getValue(); res.setContentType(ct); res.setEncodingAndType(ct); } HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); res.setResponseData(readResponse(res, instream, (int) entity.getContentLength())); } res.sampleEnd(); // Done with the sampling proper. currentRequest = null; // Now collect the results into the HTTPSampleResult: StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); res.setResponseCode(Integer.toString(statusCode)); res.setResponseMessage(statusLine.getReasonPhrase()); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseHeaders(getResponseHeaders(httpResponse)); if (res.isRedirect()) { final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException( "Missing location header in redirect for " + httpRequest.getRequestLine()); } String redirectLocation = headerLocation.getValue(); res.setRedirectLocation(redirectLocation); } // record some sizes to allow HTTPSampleResult.getBytes() with different options HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_METRICS); long headerBytes = res.getResponseHeaders().length() // condensed length (without \r) + httpResponse.getAllHeaders().length // Add \r for each header + 1 // Add \r for initial header + 2; // final \r\n before data long totalBytes = metrics.getReceivedBytesCount(); res.setHeadersSize((int) headerBytes); res.setBodySize((int) (totalBytes - headerBytes)); if (log.isDebugEnabled()) { log.debug("ResponseHeadersSize=" + res.getHeadersSize() + " Content-Length=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); URI redirectURI = req.getURI(); if (redirectURI.isAbsolute()) { res.setURL(redirectURI.toURL()); } else { res.setURL(new URL(new URL(target.toURI()), redirectURI.toString())); } } }
From source file:com.timtory.wmgallery.picasa.GDataClient.java
private void callMethod(HttpUriRequest request, Operation operation) throws IOException { try {// w w w. j a v a 2 s. c o m // Specify GData protocol version 2.0. request.addHeader("GData-Version", "2"); // Indicate support for gzip-compressed responses. request.addHeader("Accept-Encoding", "gzip"); // Specify authorization token if provided. String authToken = mAuthToken; if (!TextUtils.isEmpty(authToken)) { request.addHeader("Authorization", "GoogleLogin auth=" + authToken); } // Specify the ETag of a prior response, if available. String etag = operation.inOutEtag; if (etag != null) { request.addHeader("If-None-Match", etag); } // Execute the HTTP request. HttpResponse httpResponse = null; try { httpResponse = mHttpClient.execute(request); } catch (IOException e) { Log.w(TAG, "Request failed: " + request.getURI()); throw e; } // Get the status code and response body. int status = httpResponse.getStatusLine().getStatusCode(); InputStream stream = null; HttpEntity entity = httpResponse.getEntity(); if (entity != null) { // Wrap the entity input stream in a GZIP decoder if necessary. stream = entity.getContent(); if (stream != null) { Header header = entity.getContentEncoding(); if (header != null) { if (header.getValue().contains("gzip")) { stream = new GZIPInputStream(stream); } } } } // Return the stream if successful. Header etagHeader = httpResponse.getFirstHeader("ETag"); operation.outStatus = status; operation.inOutEtag = etagHeader != null ? etagHeader.getValue() : null; operation.outBody = stream; } catch (java.lang.IllegalStateException e) { Log.e(TAG, "Unhandled IllegalStateException e: " + e); throw new IOException("Unhandled IllegalStateException"); } }