List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader
void addHeader(Header header);
From source file:io.fabric8.elasticsearch.ElasticsearchIntegrationTest.java
protected HttpResponse executeRequest(HttpUriRequest uriRequest, Header... header) throws Exception { CloseableHttpClient httpClient = null; try {/*from w w w .j a v a2 s . com*/ httpClient = getHttpClient(); if (header != null && header.length > 0) { for (int i = 0; i < header.length; i++) { Header h = header[i]; uriRequest.addHeader(h); } } HttpResponse res = new HttpResponse(httpClient.execute(uriRequest)); log.trace(res.getBody()); return res; } finally { if (httpClient != null) { httpClient.close(); } } }
From source file:org.ovirt.engine.sdk.web.HttpProxy.java
/** * Injects HTTP headers in to request//from ww w. j a v a 2 s. c o m * * @param request * @param headers */ private void injectHeaders(HttpUriRequest request, List<Header> headers) { List<Header> updated = excludeNullHeaders(headers); if (updated != null && !updated.isEmpty()) { request.setHeaders(updated.toArray(new Header[updated.size()])); } // The Apache web server ignores the "Expect" header, so if this header was explicitly added by the user, then // we need to add the alternative "X-Ovirt-Expect" as well: if (headers != null) { for (Header header : headers) { if (EXPECT_HEADER.equalsIgnoreCase(header.getName())) { request.setHeader(ALTERNATIVE_EXPECT_HEADER, header.getValue()); } } } // inject .ctr defined static parameters for (Header header : this.staticHeaders) { if (header.getName().equals(CONTENT_TYPE_HEADER)) { if ((request instanceof HttpDelete) && ((HttpDelete) request).getEntity() == null) { continue; } else if ((request instanceof HttpPut) && ((HttpPut) request).getEntity() == null) { continue; } else if ((request instanceof HttpPost) && ((HttpPost) request).getEntity() == null) { continue; } } request.addHeader(header); } // inject FILTER_HEADER request.addHeader(FILTER_HEADER, Boolean.toString(isFilter())); if (this.persistentAuth) { // inject PERSISTENT_AUTH_HEADER request.addHeader(PERSISTENT_AUTH_HEADER, PERSISTENT_AUTH_HEADER_CONTENT); // inject COOKIE_HEADER if JSESSION provided explicitly if (!StringUtils.isNulOrEmpty(this.sessionid)) { request.addHeader(COOKIE_HEADER, this.sessionid); } // inject authentication session inactivity timeout if (this.pool.getSessionTimeout() != null) { request.addHeader(SESSION_TTL_HEADER, String.valueOf(this.pool.getSessionTimeout())); } } }
From source file:org.seasar.robot.client.http.HcHttpClient.java
protected ResponseData processHttpMethod(final String url, final HttpUriRequest httpRequest) { try {// w w w .jav a 2s . com processRobotsTxt(url); } catch (final RobotCrawlAccessException e) { if (logger.isInfoEnabled()) { final StringBuilder buf = new StringBuilder(); buf.append(e.getMessage()); if (e.getCause() != null) { buf.append(e.getCause().getMessage()); } logger.info(buf.toString()); } else if (logger.isDebugEnabled()) { logger.debug("Crawling Access Exception at " + url, e); } } // request header for (final Header header : requestHeaderList) { httpRequest.addHeader(header); } ResponseData responseData = null; InputStream inputStream = null; HttpEntity httpEntity = null; try { // get a content final HttpResponse response = executeHttpClient(httpRequest); httpEntity = response.getEntity(); final int httpStatusCode = response.getStatusLine().getStatusCode(); // redirect if (isRedirectHttpStatus(httpStatusCode)) { final Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { logger.warn("Invalid redirect location at " + url); } else { responseData = new ResponseData(); responseData.setRedirectLocation(locationHeader.getValue()); return responseData; } } long contentLength = 0; String contentEncoding = Constants.UTF_8; if (httpEntity == null) { inputStream = new ByteArrayInputStream(new byte[0]); } else { final InputStream responseBodyStream = httpEntity.getContent(); final File outputFile = File.createTempFile("s2robot-HcHttpClient-", ".out"); DeferredFileOutputStream dfos = null; try { try { dfos = new DeferredFileOutputStream(responseBodyInMemoryThresholdSize, outputFile); StreamUtil.drain(responseBodyStream, dfos); dfos.flush(); } finally { IOUtils.closeQuietly(dfos); } } catch (final Exception e) { if (!outputFile.delete()) { logger.warn("Could not delete " + outputFile.getAbsolutePath()); } throw e; } if (dfos.isInMemory()) { inputStream = new ByteArrayInputStream(dfos.getData()); contentLength = dfos.getData().length; if (!outputFile.delete()) { logger.warn("Could not delete " + outputFile.getAbsolutePath()); } } else { inputStream = new TemporaryFileInputStream(outputFile); contentLength = outputFile.length(); } final Header contentEncodingHeader = httpEntity.getContentEncoding(); if (contentEncodingHeader != null) { contentEncoding = contentEncodingHeader.getValue(); } } String contentType = null; final Header contentTypeHeader = response.getFirstHeader("Content-Type"); if (contentTypeHeader != null) { contentType = contentTypeHeader.getValue(); final int idx = contentType.indexOf(';'); if (idx > 0) { contentType = contentType.substring(0, idx); } } // check file size if (contentLengthHelper != null) { final long maxLength = contentLengthHelper.getMaxLength(contentType); if (contentLength > maxLength) { throw new MaxLengthExceededException("The content length (" + contentLength + " byte) is over " + maxLength + " byte. The url is " + url); } } responseData = new ResponseData(); responseData.setUrl(url); responseData.setCharSet(contentEncoding); if (httpRequest instanceof HttpHead) { responseData.setMethod(Constants.HEAD_METHOD); } else { responseData.setMethod(Constants.GET_METHOD); } responseData.setResponseBody(inputStream); responseData.setHttpStatusCode(httpStatusCode); for (final Header header : response.getAllHeaders()) { responseData.addMetaData(header.getName(), header.getValue()); } if (contentType == null) { responseData.setMimeType(defaultMimeType); } else { responseData.setMimeType(contentType); } final Header contentLengthHeader = response.getFirstHeader("Content-Length"); if (contentLengthHeader == null) { responseData.setContentLength(contentLength); } else { final String value = contentLengthHeader.getValue(); try { responseData.setContentLength(Long.parseLong(value)); } catch (final Exception e) { responseData.setContentLength(contentLength); } } final Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); if (lastModifiedHeader != null) { final String value = lastModifiedHeader.getValue(); if (StringUtil.isNotBlank(value)) { final Date d = parseLastModified(value); if (d != null) { responseData.setLastModified(d); } } } if (responseData.getLastModified() == null) { responseData.setLastModified(new Date()); // set current time } return responseData; } catch (final UnknownHostException e) { httpRequest.abort(); IOUtils.closeQuietly(inputStream); throw new RobotCrawlAccessException("Unknown host(" + e.getMessage() + "): " + url, e); } catch (final NoRouteToHostException e) { httpRequest.abort(); IOUtils.closeQuietly(inputStream); throw new RobotCrawlAccessException("No route to host(" + e.getMessage() + "): " + url, e); } catch (final ConnectException e) { httpRequest.abort(); IOUtils.closeQuietly(inputStream); throw new RobotCrawlAccessException("Connection time out(" + e.getMessage() + "): " + url, e); } catch (final SocketException e) { httpRequest.abort(); IOUtils.closeQuietly(inputStream); throw new RobotCrawlAccessException("Socket exception(" + e.getMessage() + "): " + url, e); } catch (final IOException e) { httpRequest.abort(); IOUtils.closeQuietly(inputStream); throw new RobotCrawlAccessException("I/O exception(" + e.getMessage() + "): " + url, e); } catch (final RobotSystemException e) { httpRequest.abort(); IOUtils.closeQuietly(inputStream); throw e; } catch (final Exception e) { httpRequest.abort(); IOUtils.closeQuietly(inputStream); throw new RobotSystemException("Failed to access " + url, e); } finally { EntityUtils.consumeQuietly(httpEntity); } }
From source file:org.vietspider.net.apache.DefaultRequestDirector.java
/** * Analyzes a response to check need for a followup. * * @param roureq the request and route. * @param response the response to analayze * @param context the context used for the current request execution * * @return the followup request and route if there is a followup, or * <code>null</code> if the response should be returned as is * * @throws HttpException in case of a problem * @throws IOException in case of an IO problem *//*from w w w . java 2s . c om*/ protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context) throws HttpException, IOException { HttpRoute route = roureq.getRoute(); RequestWrapper request = roureq.getRequest(); HttpParams params = request.getParams(); if (HttpClientParams.isRedirecting(params) && this.redirectStrategy.isRedirected(request, response, context)) { if (redirectCount >= maxRedirects) { throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded"); } redirectCount++; // Virtual host cannot be used any longer virtualHost = null; HttpUriRequest redirect = redirectStrategy.getRedirect(request, response, context); HttpRequest orig = request.getOriginal(); // redirect.setHeaders(orig.getAllHeaders()); //VietSpider fix bug URI uri = redirect.getURI(); Header[] headers = orig.getAllHeaders(); for (Header header : headers) { if ("host".equalsIgnoreCase(header.getName())) { redirect.addHeader(new BasicHeader("Host", uri.getHost())); } else { redirect.addHeader(header); } } if (uri.getHost() == null) { throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri); } HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); // Unset auth scope targetAuthState.setAuthScope(null); proxyAuthState.setAuthScope(null); // Invalidate auth states if redirecting to another host if (!route.getTargetHost().equals(newTarget)) { targetAuthState.invalidate(); AuthScheme authScheme = proxyAuthState.getAuthScheme(); if (authScheme != null && authScheme.isConnectionBased()) { proxyAuthState.invalidate(); } } RequestWrapper wrapper = wrapRequest(redirect); wrapper.setParams(params); HttpRoute newRoute = determineRoute(newTarget, wrapper, context); RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute); if (this.log.isDebugEnabled()) { this.log.debug("Redirecting to '" + uri + "' via " + newRoute); } return newRequest; } CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { if (this.targetAuthHandler.isAuthenticationRequested(response, context)) { HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target == null) { target = route.getTargetHost(); } this.log.debug("Target requested authentication"); Map<String, Header> challenges = this.targetAuthHandler.getChallenges(response, context); try { processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context); } catch (AuthenticationException ex) { if (this.log.isWarnEnabled()) { this.log.warn("Authentication error: " + ex.getMessage()); return null; } } updateAuthState(this.targetAuthState, target, credsProvider); if (this.targetAuthState.getCredentials() != null) { // Re-try the same request via the same route return roureq; } else { return null; } } else { // Reset target auth scope this.targetAuthState.setAuthScope(null); } if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { HttpHost proxy = route.getProxyHost(); this.log.debug("Proxy requested authentication"); Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context); try { processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context); } catch (AuthenticationException ex) { if (this.log.isWarnEnabled()) { this.log.warn("Authentication error: " + ex.getMessage()); return null; } } updateAuthState(this.proxyAuthState, proxy, credsProvider); if (this.proxyAuthState.getCredentials() != null) { // Re-try the same request via the same route return roureq; } else { return null; } } else { // Reset proxy auth scope this.proxyAuthState.setAuthScope(null); } } return null; }
From source file:org.codelibs.fess.crawler.client.http.HcHttpClient.java
protected ResponseData processHttpMethod(final String url, final HttpUriRequest httpRequest) { try {/*from w ww . j av a 2s .co m*/ processRobotsTxt(url); } catch (final CrawlingAccessException e) { if (logger.isInfoEnabled()) { final StringBuilder buf = new StringBuilder(100); buf.append(e.getMessage()); if (e.getCause() != null) { buf.append(e.getCause().getMessage()); } logger.info(buf.toString()); } else if (logger.isDebugEnabled()) { logger.debug("Crawling Access Exception at " + url, e); } } // request header for (final Header header : requestHeaderList) { httpRequest.addHeader(header); } ResponseData responseData = new ResponseData(); HttpEntity httpEntity = null; try { // get a content final HttpResponse response = executeHttpClient(httpRequest); httpEntity = response.getEntity(); final int httpStatusCode = response.getStatusLine().getStatusCode(); // redirect if (isRedirectHttpStatus(httpStatusCode)) { final Header locationHeader = response.getFirstHeader("location"); if (locationHeader == null) { logger.warn("Invalid redirect location at " + url); } else { responseData = new ResponseData(); responseData.setRedirectLocation(locationHeader.getValue()); return responseData; } } String contentType = null; final Header contentTypeHeader = response.getFirstHeader("Content-Type"); if (contentTypeHeader != null) { contentType = contentTypeHeader.getValue(); final int idx = contentType.indexOf(';'); if (idx > 0) { contentType = contentType.substring(0, idx); if (APPLICATION_OCTET_STREAM.equals(contentType)) { contentType = null; } } } long contentLength = 0; String contentEncoding = Constants.UTF_8; if (httpEntity == null) { responseData.setResponseBody(new byte[0]); if (contentType == null) { contentType = defaultMimeType; } } else { final InputStream responseBodyStream = httpEntity.getContent(); final File outputFile = File.createTempFile("crawler-HcHttpClient-", ".out"); DeferredFileOutputStream dfos = null; try { try { dfos = new DeferredFileOutputStream((int) maxCachedContentSize, outputFile); CopyUtil.copy(responseBodyStream, dfos); dfos.flush(); } finally { IOUtils.closeQuietly(dfos); } } catch (final Exception e) { if (!outputFile.delete()) { logger.warn("Could not delete " + outputFile.getAbsolutePath()); } throw e; } if (dfos.isInMemory()) { responseData.setResponseBody(dfos.getData()); contentLength = dfos.getData().length; if (!outputFile.delete()) { logger.warn("Could not delete " + outputFile.getAbsolutePath()); } if (contentType == null) { try (InputStream is = new ByteArrayInputStream(dfos.getData())) { contentType = mimeTypeHelper.getContentType(is, url); } catch (Exception e) { logger.debug("Failed to detect mime-type.", e); contentType = defaultMimeType; } } } else { responseData.setResponseBody(outputFile, true); contentLength = outputFile.length(); if (contentType == null) { try (InputStream is = new FileInputStream(outputFile)) { contentType = mimeTypeHelper.getContentType(is, url); } catch (Exception e) { logger.debug("Failed to detect mime-type.", e); contentType = defaultMimeType; } } } final Header contentEncodingHeader = httpEntity.getContentEncoding(); if (contentEncodingHeader != null) { contentEncoding = contentEncodingHeader.getValue(); } } // check file size if (contentLengthHelper != null) { final long maxLength = contentLengthHelper.getMaxLength(contentType); if (contentLength > maxLength) { throw new MaxLengthExceededException("The content length (" + contentLength + " byte) is over " + maxLength + " byte. The url is " + url); } } responseData.setUrl(url); responseData.setCharSet(contentEncoding); if (httpRequest instanceof HttpHead) { responseData.setMethod(Constants.HEAD_METHOD); } else { responseData.setMethod(Constants.GET_METHOD); } responseData.setHttpStatusCode(httpStatusCode); for (final Header header : response.getAllHeaders()) { responseData.addMetaData(header.getName(), header.getValue()); } responseData.setMimeType(contentType); final Header contentLengthHeader = response.getFirstHeader("Content-Length"); if (contentLengthHeader == null) { responseData.setContentLength(contentLength); } else { final String value = contentLengthHeader.getValue(); try { responseData.setContentLength(Long.parseLong(value)); } catch (final Exception e) { responseData.setContentLength(contentLength); } } checkMaxContentLength(responseData); final Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); if (lastModifiedHeader != null) { final String value = lastModifiedHeader.getValue(); if (StringUtil.isNotBlank(value)) { final Date d = parseLastModified(value); if (d != null) { responseData.setLastModified(d); } } } return responseData; } catch (final UnknownHostException e) { closeResources(httpRequest, responseData); throw new CrawlingAccessException("Unknown host(" + e.getMessage() + "): " + url, e); } catch (final NoRouteToHostException e) { closeResources(httpRequest, responseData); throw new CrawlingAccessException("No route to host(" + e.getMessage() + "): " + url, e); } catch (final ConnectException e) { closeResources(httpRequest, responseData); throw new CrawlingAccessException("Connection time out(" + e.getMessage() + "): " + url, e); } catch (final SocketException e) { closeResources(httpRequest, responseData); throw new CrawlingAccessException("Socket exception(" + e.getMessage() + "): " + url, e); } catch (final IOException e) { closeResources(httpRequest, responseData); throw new CrawlingAccessException("I/O exception(" + e.getMessage() + "): " + url, e); } catch (final CrawlerSystemException e) { closeResources(httpRequest, responseData); throw e; } catch (final Exception e) { closeResources(httpRequest, responseData); throw new CrawlerSystemException("Failed to access " + url, e); } finally { EntityUtils.consumeQuietly(httpEntity); } }
From source file:org.openestate.is24.restapi.hc43.HttpComponents43Client.java
@Override protected Response sendVideoUploadRequest(URL url, RequestMethod method, String auth, InputStream input, String fileName, final long fileSize) throws IOException, OAuthException { if (method == null) method = RequestMethod.POST;/* ww w. j av a2s .c o m*/ if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method)) throw new IllegalArgumentException("Invalid request method!"); HttpUriRequest request = null; if (RequestMethod.POST.equals(method)) { request = new HttpPost(url.toString()); } else if (RequestMethod.PUT.equals(method)) { request = new HttpPut(url.toString()); } else { throw new IOException("Unsupported request method '" + method + "'!"); } MultipartEntityBuilder b = MultipartEntityBuilder.create(); // add auth part to the multipart entity auth = StringUtils.trimToNull(auth); if (auth != null) { //StringBody authPart = new StringBody( // auth, ContentType.create( "text/plain", getEncoding() ) ); //b.addPart( "auth", authPart ); b.addTextBody("auth", auth, ContentType.create("text/plain", getEncoding())); } // add file part to the multipart entity if (input != null) { fileName = StringUtils.trimToNull(fileName); if (fileName == null) fileName = "upload.bin"; //InputStreamBody filePart = new InputStreamBody( input, fileName ); InputStreamBody filePart = new InputStreamBodyWithLength(input, fileName, fileSize); b.addPart("videofile", filePart); } // add multipart entity to the request HttpEntity requestMultipartEntity = b.build(); request.setHeader("MIME-Version", "1.0"); request.addHeader(requestMultipartEntity.getContentType()); request.setHeader("Content-Language", "en-US"); request.setHeader("Accept-Charset", "UTF-8"); request.setHeader("Accept-Encoding", "gzip,deflate"); request.setHeader("Connection", "close"); ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity); // sign request //getAuthConsumer().sign( request ); // send request HttpResponse response = httpClient.execute(request); // create response return createResponse(response); }
From source file:org.elasticsearch.client.RestClientSingleHostTests.java
private HttpUriRequest performRandomRequest(String method) throws Exception { String uriAsString = "/" + randomStatusCode(getRandom()); URIBuilder uriBuilder = new URIBuilder(uriAsString); final Map<String, String> params = new HashMap<>(); boolean hasParams = randomBoolean(); if (hasParams) { int numParams = randomIntBetween(1, 3); for (int i = 0; i < numParams; i++) { String paramKey = "param-" + i; String paramValue = randomAsciiOfLengthBetween(3, 10); params.put(paramKey, paramValue); uriBuilder.addParameter(paramKey, paramValue); }/*from w w w . j a va 2 s. com*/ } if (randomBoolean()) { //randomly add some ignore parameter, which doesn't get sent as part of the request String ignore = Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes())); if (randomBoolean()) { ignore += "," + Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes())); } params.put("ignore", ignore); } URI uri = uriBuilder.build(); HttpUriRequest request; switch (method) { case "DELETE": request = new HttpDeleteWithEntity(uri); break; case "GET": request = new HttpGetWithEntity(uri); break; case "HEAD": request = new HttpHead(uri); break; case "OPTIONS": request = new HttpOptions(uri); break; case "PATCH": request = new HttpPatch(uri); break; case "POST": request = new HttpPost(uri); break; case "PUT": request = new HttpPut(uri); break; case "TRACE": request = new HttpTrace(uri); break; default: throw new UnsupportedOperationException("method not supported: " + method); } HttpEntity entity = null; boolean hasBody = request instanceof HttpEntityEnclosingRequest && getRandom().nextBoolean(); if (hasBody) { entity = new StringEntity(randomAsciiOfLengthBetween(10, 100), ContentType.APPLICATION_JSON); ((HttpEntityEnclosingRequest) request).setEntity(entity); } Header[] headers = new Header[0]; final Set<String> uniqueNames = new HashSet<>(); if (randomBoolean()) { headers = RestClientTestUtil.randomHeaders(getRandom(), "Header"); for (Header header : headers) { request.addHeader(header); uniqueNames.add(header.getName()); } } for (Header defaultHeader : defaultHeaders) { // request level headers override default headers if (uniqueNames.contains(defaultHeader.getName()) == false) { request.addHeader(defaultHeader); } } try { if (hasParams == false && hasBody == false && randomBoolean()) { restClient.performRequest(method, uriAsString, headers); } else if (hasBody == false && randomBoolean()) { restClient.performRequest(method, uriAsString, params, headers); } else { restClient.performRequest(method, uriAsString, params, entity, headers); } } catch (ResponseException e) { //all good } return request; }
From source file:org.openestate.is24.restapi.hc43.HttpComponents43Client.java
@Override protected Response sendXmlAttachmentRequest(URL url, RequestMethod method, String xml, InputStream input, String fileName, String mimeType) throws IOException, OAuthException { if (method == null) method = RequestMethod.POST;//w w w .j av a 2 s.c om if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method)) throw new IllegalArgumentException("Invalid request method!"); xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml) : null; HttpUriRequest request = null; if (RequestMethod.POST.equals(method)) { request = new HttpPost(url.toString()); } else if (RequestMethod.PUT.equals(method)) { request = new HttpPut(url.toString()); } else { throw new IOException("Unsupported request method '" + method + "'!"); } MultipartEntityBuilder b = MultipartEntityBuilder.create(); // add xml part to the multipart entity if (xml != null) { //InputStreamBody xmlPart = new InputStreamBody( // new ByteArrayInputStream( xml.getBytes( getEncoding() ) ), // ContentType.parse( "application/xml" ), // "body.xml" ); //b.addPart( "metadata", xmlPart ); b.addTextBody("metadata", xml, ContentType.create("application/xml", getEncoding())); } // add file part to the multipart entity if (input != null) { mimeType = StringUtils.trimToNull(mimeType); if (mimeType == null) mimeType = "application/octet-stream"; fileName = StringUtils.trimToNull(fileName); if (fileName == null) fileName = "upload.bin"; //InputStreamBody filePart = new InputStreamBody( // input, ContentType.create( mimeType ), fileName ); //b.addPart( "attachment", filePart ); b.addBinaryBody("attachment", input, ContentType.create(mimeType), fileName); } // add multipart entity to the request HttpEntity requestMultipartEntity = b.build(); request.addHeader(requestMultipartEntity.getContentType()); request.setHeader("Content-Language", "en-US"); request.setHeader("Accept", "application/xml"); ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity); // sign request getAuthConsumer().sign(request); // send request HttpResponse response = httpClient.execute(request); // create response return createResponse(response); }
From source file:com.llkj.cm.restfull.network.NetworkConnection.java
private static NetworkConnectionResult retrieveResponseFromService(final String url, final int method, final Map<String, String> parameters, final ArrayList<Header> headers, final boolean isGzipEnabled, final String userAgent, final String postText, final ArrayList<String> previousUrlList, int connectionTimeout, int soTimeout) throws IllegalStateException, IOException, URISyntaxException, RestClientException { // Get the request URL if (url == null) { if (LogConfig.DP_ERROR_LOGS_ENABLED) { Log.e(LOG_TAG, "retrieveResponseFromService - Compulsory Parameter : request URL has not been set"); }//from w w w . j av a2 s .c om throw new CompulsoryParameterException("Request URL has not been set"); } if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Request url : " + url); } // Get the request method if (method != METHOD_GET && method != METHOD_POST && method != METHOD_PUT && method != METHOD_DELETE) { if (LogConfig.DP_ERROR_LOGS_ENABLED) { Log.e(LOG_TAG, "retrieveResponseFromService - Request method must be METHOD_GET, METHOD_POST, METHOD_PUT or METHOD_DELETE"); } throw new IllegalArgumentException( "retrieveResponseFromService - Request method must be METHOD_GET, METHOD_POST, METHOD_PUT or METHOD_DELETE"); } if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Request method : " + method); } // Get the request parameters if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Request parameters (number) : " + ((parameters != null) ? parameters.size() : "")); } // Get the request headers if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Request headers (number) : " + ((headers != null) ? headers.size() : "")); } // Create the Request final AndroidHttpClient client = AndroidHttpClient .newInstance(userAgent != null ? userAgent : sDefaultUserAgent); if (connectionTimeout != -1) { HttpConnectionParams.setConnectionTimeout(client.getParams(), connectionTimeout); } if (soTimeout != -1) { HttpConnectionParams.setSoTimeout(client.getParams(), soTimeout); } if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Request user agent : " + userAgent); } try { HttpUriRequest request = null; switch (method) { case METHOD_GET: case METHOD_DELETE: { final StringBuffer sb = new StringBuffer(); sb.append(url); // Add the parameters to the GET url if any if (parameters != null && !parameters.isEmpty()) { sb.append("&"); final ArrayList<String> keyList = new ArrayList<String>(parameters.keySet()); final int keyListLength = keyList.size(); for (int i = 0; i < keyListLength; i++) { final String key = keyList.get(i); sb.append(URLEncoder.encode(key, "UTF-8")); sb.append("="); sb.append(URLEncoder.encode(parameters.get(key), "UTF-8")); sb.append("&"); } } if (LogConfig.DP_INFO_LOGS_ENABLED) { Log.i(LOG_TAG, "retrieveResponseFromService - GET Request - complete URL with parameters if any : "); final String completeUrl = sb.toString(); int pos = 0; int dumpLength = completeUrl.length(); while (pos < dumpLength) { Log.i(LOG_TAG, completeUrl.substring(pos, Math.min(dumpLength - 1, pos + 120))); pos = pos + 120; } } final URI uri = new URI(sb.toString()); if (method == METHOD_GET) { request = new HttpGet(uri); } else if (method == METHOD_DELETE) { request = new HttpDelete(uri); } break; } case METHOD_POST: case METHOD_PUT: { final URI uri = new URI(url); if (method == METHOD_POST) { request = new HttpPost(uri); } else if (method == METHOD_PUT) { request = new HttpPut(uri); } // Add the parameters to the POST request if any if (parameters != null && !parameters.isEmpty()) { final List<NameValuePair> postRequestParameters = new ArrayList<NameValuePair>(); final ArrayList<String> keyList = new ArrayList<String>(parameters.keySet()); final int keyListLength = keyList.size(); for (int i = 0; i < keyListLength; i++) { final String key = keyList.get(i); postRequestParameters.add(new BasicNameValuePair(key, parameters.get(key))); } if (LogConfig.DP_INFO_LOGS_ENABLED) { Log.i(LOG_TAG, "retrieveResponseFromService - POST Request - parameters list (key => value) : "); final int postRequestParametersLength = postRequestParameters.size(); for (int i = 0; i < postRequestParametersLength; i++) { final NameValuePair nameValuePair = postRequestParameters.get(i); Log.i(LOG_TAG, "- " + nameValuePair.getName() + " => " + nameValuePair.getValue()); } } request.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); if (method == METHOD_POST) { ((HttpPost) request).setEntity(new UrlEncodedFormEntity(postRequestParameters, "UTF-8")); } else if (method == METHOD_PUT) { ((HttpPut) request).setEntity(new UrlEncodedFormEntity(postRequestParameters, "UTF-8")); } } else if (null != postText) { // Add post text (send xml // for // example) if (method == METHOD_POST) { ((HttpPost) request).setEntity(new StringEntity(postText)); } else if (method == METHOD_PUT) { ((HttpPut) request).setEntity(new StringEntity(postText)); } } break; } default: { if (LogConfig.DP_ERROR_LOGS_ENABLED) { Log.e(LOG_TAG, "retrieveResponseFromService - Request method must be METHOD_GET, METHOD_POST, METHOD_PUT or METHOD_DELETE"); } throw new IllegalArgumentException( "retrieveResponseFromService - Request method must be METHOD_GET, METHOD_POST, METHOD_PUT or METHOD_DELETE"); } } // Activate the gzip compression if asked if (isGzipEnabled) { AndroidHttpClient.modifyRequestToAcceptGzipResponse(request); } if (LogConfig.DP_INFO_LOGS_ENABLED) { Log.i(LOG_TAG, "retrieveResponseFromService - Request - headers list (name => value) : "); final HeaderIterator iterator = request.headerIterator(); while (iterator.hasNext()) { final Header header = iterator.nextHeader(); Log.i(LOG_TAG, "- " + header.getName() + " => " + header.getValue()); } } // Add the request headers if any if (headers != null && !headers.isEmpty()) { final int headersLength = headers.size(); for (int i = 0; i < headersLength; i++) { request.addHeader(headers.get(i)); } } // Launch the request String result = null; if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Executing the request"); } final HttpResponse response = client.execute(request); // Get the response status final StatusLine status = response.getStatusLine(); if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Response status : " + status.getStatusCode()); } final int statusCode = status.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { if (LogConfig.DP_ERROR_LOGS_ENABLED) { Log.e(LOG_TAG, "retrieveResponseFromService - Invalid response from server : " + status.toString()); } if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { final Header newLocation = response.getFirstHeader("Location"); if (LogConfig.DP_INFO_LOGS_ENABLED) { Log.i(LOG_TAG, "retrieveResponseFromService - New location : " + newLocation.getValue()); } NewLocation.noticeNewLocation(newLocation.getValue(), url); // throw new RestClientException("New location : " + newLocation, newLocation.getValue()); } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) { if (method == METHOD_GET) { final String newUrl = response.getHeaders("Location")[0].getValue(); if (!previousUrlList.contains(newUrl)) { Log.d(LOG_TAG, "retrieveResponseFromService - Url moved permanently - Trying the new url : " + newUrl); previousUrlList.add(newUrl); return retrieveResponseFromService(newUrl, method, parameters, headers, isGzipEnabled, userAgent, postText); } else { // It's an url already checked. We are in a loop. So let's throw an Exception throw new RestClientException("Moved permanently - Loop detected", statusCode); } } else { throw new RestClientException("Invalid response from server : ", statusCode); } } else { throw new RestClientException("Invalid response from server : ", statusCode); } } // Get the response entity final HttpEntity entity = response.getEntity(); final Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (entity != null) { result = convertStreamToString(entity.getContent(), contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip"), method, (int) entity.getContentLength()); } if (LogConfig.DP_INFO_LOGS_ENABLED) { Log.i(LOG_TAG, "retrieveResponseFromService - Result from webservice : " + result); } return new NetworkConnectionResult(statusCode, response.getAllHeaders(), result); } finally { client.close(); } }