List of usage examples for org.apache.http.client.methods HttpRequestBase setHeader
public void setHeader(String str, String str2)
From source file:cn.isif.util_plus.http.HttpHandler.java
@SuppressWarnings("unchecked") private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException { HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (true) { if (autoResume && isDownloadingFile) { File downloadFile = new File(fileSavePath); long fileLen = 0; if (downloadFile.isFile() && downloadFile.exists()) { fileLen = downloadFile.length(); }//from ww w .j av a2 s .co m if (fileLen > 0) { request.setHeader("RANGE", "bytes=" + fileLen + "-"); } } boolean retry = true; IOException exception = null; try { requestMethod = request.getMethod(); if (HttpUtils.sHttpCache.isEnabled(requestMethod)) { String result = HttpUtils.sHttpCache.get(requestUrl); if (result != null) { return new ResponseInfo<T>(null, (T) result, true); } } ResponseInfo<T> responseInfo = null; if (!isCancelled()) { HttpResponse response = client.execute(request, context); responseInfo = handleResponse(response); } return responseInfo; } catch (UnknownHostException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (IOException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (NullPointerException e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (HttpException e) { throw e; } catch (Throwable e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } if (!retry) { throw new HttpException(exception); } } }
From source file:com.oakesville.mythling.util.MediaStreamProxy.java
private HttpResponse download() throws IOException { httpClient = AndroidHttpClient.newInstance("Android"); // httpClient.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost("127.0.0.1")); URL netUrl = proxyInfo.netUrl; HttpHost host = new HttpHost(netUrl.getHost(), netUrl.getPort(), netUrl.getProtocol()); HttpRequestBase request = new HttpGet(netUrl.toString()); HttpResponse response = null;//from ww w. j a v a 2s . co m Log.d(TAG, "Proxy starting download"); if (authType == AuthType.Digest) { HttpContext context = HttpHelper.getDigestAuthContext(netUrl.getHost(), netUrl.getPort(), proxyInfo.user, proxyInfo.password); response = httpClient.execute(host, request, context); } else if (authType == AuthType.Basic) { String credentials = Base64.encodeToString((proxyInfo.user + ":" + proxyInfo.password).getBytes(), Base64.DEFAULT); request.setHeader("Authorization", "Basic " + credentials); response = httpClient.execute(host, request); } else { response = httpClient.execute(host, request); } Log.d(TAG, "Proxy response downloaded"); return response; }
From source file:com.drive.student.xutils.http.HttpHandler.java
@SuppressWarnings("unchecked") private com.drive.student.xutils.http.ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException { HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (true) { if (autoResume && isDownloadingFile) { File downloadFile = new File(fileSavePath); long fileLen = 0; if (downloadFile.isFile() && downloadFile.exists()) { fileLen = downloadFile.length(); }//from w w w .j ava 2 s . c o m if (fileLen > 0) { request.setHeader("RANGE", "bytes=" + fileLen + "-"); } } boolean retry = true; IOException exception = null; try { requestMethod = request.getMethod(); if (HttpUtils.sHttpCache.isEnabled(requestMethod)) { String result = HttpUtils.sHttpCache.get(requestUrl); if (result != null) { return new com.drive.student.xutils.http.ResponseInfo<T>(null, (T) result, true); } } com.drive.student.xutils.http.ResponseInfo<T> responseInfo = null; if (!isCancelled()) { HttpResponse response = client.execute(request, context); responseInfo = handleResponse(response); } return responseInfo; } catch (UnknownHostException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (IOException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (NullPointerException e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (HttpException e) { throw e; } catch (Throwable e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } if (!retry) { throw new HttpException(exception); } } }
From source file:com.adis.tools.http.HttpHandler.java
@SuppressWarnings("unchecked") private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException { HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (true) { if (autoResume && isDownloadingFile) { downloadFile = new File(fileSavePath); fileLen = 0;/*from w w w . j a v a 2 s. c o m*/ if (downloadFile.isFile() && downloadFile.exists()) { fileLen = downloadFile.length(); } if (fileLen > 0) { request.setHeader("RANGE", "bytes=" + fileLen + "-"); } } boolean retry = true; IOException exception = null; try { requestMethod = request.getMethod(); if (HttpUtils.sHttpCache.isEnabled(requestMethod)) { String result = HttpUtils.sHttpCache.get(requestUrl); if (result != null) { return new ResponseInfo<T>(null, (T) result, true); } } ResponseInfo<T> responseInfo = null; if (!isCancelled()) { HttpResponse response = client.execute(request, context); responseInfo = handleResponse(response); } return responseInfo; } catch (UnknownHostException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (IOException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (NullPointerException e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } catch (HttpException e) { throw e; } catch (Throwable e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedCount, context); } if (!retry) { throw new HttpException(exception); } } }
From source file:com.faceture.rest.RestClientUtil.java
public RestResponse doRequest(HttpRequestBase httpRequest, boolean https, String hostName, String path, Map<String, String> queryParams, Map<String, String> httpHeaders, Map<String, String> cookies) throws URISyntaxException, IOException { if (null == httpRequest) { throw new IllegalArgumentException("httpRequest is null"); }/*from ww w. j a va2s . c om*/ if (null == hostName || hostName.isEmpty()) { throw new IllegalArgumentException("hostName is null or empty"); } if (null == path || path.isEmpty()) { throw new IllegalArgumentException("path is null or empty"); } // set the headers -- optional if (httpHeaders != null && !httpHeaders.isEmpty()) { httpUtil.setHeaders(httpRequest, httpHeaders); } httpRequest.setHeader("User-Agent", ""); // get the query string -- optional String queryString = null; if (queryParams != null && !queryParams.isEmpty()) { queryString = httpUtil.getQueryString(queryParams); } // set the URI httpUtil.setUri(httpRequest, https, hostName, path, queryString); // get the HTTP Client DefaultHttpClient httpClient = httpClientFactory.createHttpClient(); // set the cookies -- optional if (cookies != null && !cookies.isEmpty()) { httpUtil.setCookies(httpRequest, cookies); } HttpResponse httpResponse = httpUtil.execute(httpClient, httpRequest); String responseBody = httpUtil.getResponseString(httpResponse); int statusCode = httpResponse.getStatusLine().getStatusCode(); // get the cookies returned in the response cookies = httpUtil.getCookies(httpClient); // get the headers returned in the response httpHeaders = httpUtil.getHeaders(httpResponse); // return the response return restResponseFactory.create(statusCode, cookies, httpHeaders, responseBody); }
From source file:ro.zg.netcell.datasources.executors.http.HttpCommandExecutor.java
public HttpCommandResponse executeCommand(CommandContext commandContext) throws Exception { HttpClient httpClient = (HttpClient) commandContext.getConnectionManager().getConnection(); ScriptDaoCommand command = commandContext.getCommand(); String method = (String) command.getArgument("method"); String url = (String) command.getArgument("url"); /* encode the url passed on the http request */ // URI requestUri = new URI(url); // requestUri = URIUtils.createURI(requestUri.getScheme(), requestUri.getHost(), requestUri.getPort(), // requestUri.getPath(), URLEncoder.encode(requestUri.getQuery(),HTTP.DEFAULT_PROTOCOL_CHARSET), // requestUri.getFragment()); String encodedUrl = URLEncoder.encode(url, HTTP.DEFAULT_PROTOCOL_CHARSET); boolean returnHeaders = false; Object rh = command.getArgument("returnHeaders"); if (rh != null) { returnHeaders = (Boolean) rh; }//from ww w .j a v a2 s .c o m HttpRequestBase request = null; if ("GET".equals(method)) { request = new HttpGet(encodedUrl); } else if ("POST".equals(method)) { HttpPost post = new HttpPost(encodedUrl); String content = (String) command.getArgument("content"); if (content != null) { post.setEntity(new StringEntity(content)); } request = post; } else if ("HEAD".equals(method)) { request = new HttpHead(encodedUrl); } Map<String, String> requestHeaders = (Map) command.getArgument("requestHeaders"); if (requestHeaders != null) { for (Map.Entry<String, String> entry : requestHeaders.entrySet()) { request.setHeader(entry.getKey(), entry.getValue()); } } HttpContext localContext = new BasicHttpContext(); HttpEntity responseEntity = null; HttpCommandResponse commandResponse = new HttpCommandResponse(); try { HttpResponse response = httpClient.execute(request, localContext); responseEntity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); commandResponse.setStatusCode(statusLine.getStatusCode()); commandResponse.setProtocol(statusLine.getProtocolVersion().getProtocol()); commandResponse.setReasonPhrase(statusLine.getReasonPhrase()); commandResponse.setRequestUrl(url); HttpRequest actualRequest = (HttpRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); commandResponse.setTargetUrl(targetHost.toURI() + actualRequest.getRequestLine().getUri()); if (returnHeaders) { Map<String, String> headers = new HashMap<String, String>(); for (Header h : response.getAllHeaders()) { headers.put(h.getName().toLowerCase(), h.getValue().toLowerCase()); } commandResponse.setHeaders(headers); } if (responseEntity != null) { long responseLength = responseEntity.getContentLength(); String responseContent = EntityUtils.toString(responseEntity, HTTP.UTF_8); if (responseLength == -1) { responseLength = responseContent.length(); } commandResponse.setLength(responseLength); commandResponse.setContent(responseContent); } } finally { if (responseEntity != null) { responseEntity.consumeContent(); } else { request.abort(); } } return commandResponse; }
From source file:com.olacabs.fabric.processors.httpwriter.HttpWriter.java
private EventSet handleRequest(EventSet eventSet, String httpMethodType) throws ProcessingException { ImmutableList.Builder<Object> builder = ImmutableList.builder(); EventSet.EventFromEventBuilder eventSetBuilder = EventSet.eventFromEventBuilder(); HttpRequestBase request = null; boolean entityEnclosable = false; switch (httpMethodType) { case "get": request = createHttpGet();/*from w w w .ja v a2 s . c o m*/ break; case "post": request = createHttpPost(); entityEnclosable = true; break; case "put": request = createHttpPut(); entityEnclosable = true; break; default: log.error("Method not recognized...{}", this.getHttpMethod()); } request.setHeader("Content-Type", "application/json"); if (null != this.getHeaders()) { this.getHeaders().forEach(request::setHeader); } CloseableHttpResponse response = null; log.debug("Handling Put Request"); for (Event event : eventSet.getEvents()) { try { log.debug("Event in json format : {}", event.getJsonNode()); if (!isBulkSupported()) { if (entityEnclosable) { ((HttpEntityEnclosingRequest) request) .setEntity(new ByteArrayEntity((byte[]) event.getData())); } response = getClient().execute(request); handleResponse(response); if (shouldPublishResponse) { Event e = Event.builder() .jsonNode(getMapper().convertValue( createResponseMap(event, response, httpMethodType), JsonNode.class)) .build(); e.setProperties(event.getProperties()); eventSetBuilder.isAggregate(false).partitionId(eventSet.getPartitionId()).event(e); } } else { builder.add(event.getData()); } } catch (Exception e) { log.error("Error processing data", e); throw new ProcessingException(); } finally { close(response); } } if (isBulkSupported()) { try { log.debug("Making Bulk call as bulk is supported"); if (entityEnclosable) { ((HttpEntityEnclosingRequest) request) .setEntity(new ByteArrayEntity(getMapper().writeValueAsBytes(builder.build()))); } response = client.execute(request); handleResponse(response); } catch (Exception e) { log.error("Exception", e); throw new ProcessingException(); } finally { close(response); } } else { if (shouldPublishResponse) { return eventSetBuilder.build(); } } return null; }
From source file:net.elasticgrid.rackspace.common.RackspaceConnection.java
/** * Make a http request and process the response. This method also performs automatic retries. * * @param request the HTTP method to use (GET, POST, DELETE, etc) * @param respType the class that represents the desired/expected return type * @return the unmarshalled entity/* w ww. j a v a 2s . c o m*/ * @throws RackspaceException * @throws IOException if there is an I/O exception * @throws HttpException if there is an HTTP exception * @throws JiBXException if the result can't be unmarshalled */ @SuppressWarnings("unchecked") protected <T> T makeRequest(HttpRequestBase request, Class<T> respType) throws HttpException, IOException, JiBXException, RackspaceException { if (!authenticated) authenticate(); // add auth params, and protocol specific headers request.addHeader("X-Auth-Token", getAuthToken()); // set accept and content-type headers request.setHeader("Accept", "application/xml; charset=UTF-8"); request.setHeader("Accept-Encoding", "gzip"); request.setHeader("Content-Type", "application/xml; charset=UTF-8"); // send the request T result = null; boolean done = false; int retries = 0; boolean doRetry = false; RackspaceException error = null; do { HttpResponse response = null; if (retries > 0) logger.log(Level.INFO, "Retry #{0}: querying via {1} {2}", new Object[] { retries, request.getMethod(), request.getURI() }); else logger.log(Level.INFO, "Querying via {0} {1}", new Object[] { request.getMethod(), request.getURI() }); if (logger.isLoggable(Level.FINEST) && request instanceof HttpEntityEnclosingRequestBase) { HttpEntity entity = ((HttpEntityEnclosingRequestBase) request).getEntity(); if (entity instanceof EntityTemplate) { EntityTemplate template = (EntityTemplate) entity; ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); template.writeTo(baos); logger.log(Level.FINEST, "Request body:\n{0}", baos.toString()); } finally { IOUtils.closeQuietly(baos); } } } InputStream entityStream = null; HttpEntity entity = null; if (logger.isLoggable(Level.FINEST)) { response = getHttpClient().execute(request); entity = response.getEntity(); try { entityStream = entity.getContent(); logger.log(Level.FINEST, "Response body on " + request.getURI() + " via " + request.getMethod() + ":\n" + IOUtils.toString(entityStream)); } finally { IOUtils.closeQuietly(entityStream); } } response = getHttpClient().execute(request); int statusCode = response.getStatusLine().getStatusCode(); entity = response.getEntity(); switch (statusCode) { case 200: case 202: case 203: try { entityStream = entity.getContent(); IBindingFactory bindingFactory = BindingDirectory.getFactory(respType); IUnmarshallingContext unmarshallingCxt = bindingFactory.createUnmarshallingContext(); result = (T) unmarshallingCxt.unmarshalDocument(entityStream, "UTF-8"); } finally { entity.consumeContent(); IOUtils.closeQuietly(entityStream); } done = true; break; case 503: // service unavailable logger.log(Level.WARNING, "Service unavailable on {0} via {1}. Will retry in {2} seconds.", new Object[] { request.getURI(), request.getMethod(), Math.pow(2.0, retries + 1) }); doRetry = true; break; case 401: // unauthorized logger.warning("Not authenticated or authentication token expired. Authenticating..."); authenticate(); doRetry = true; break; case 417: throw new RackspaceException(new IllegalArgumentException("Some parameters are invalid!")); // TODO: temp hack 'til Rackspace API is fixed! case 400: case 500: default: try { entityStream = entity.getContent(); IBindingFactory bindingFactory = BindingDirectory.getFactory(CloudServersAPIFault.class); IUnmarshallingContext unmarshallingCxt = bindingFactory.createUnmarshallingContext(); CloudServersAPIFault fault = (CloudServersAPIFault) unmarshallingCxt .unmarshalDocument(entityStream, "UTF-8"); done = true; throw new RackspaceException(fault.getCode(), fault.getMessage(), fault.getDetails()); } catch (JiBXException e) { response = getHttpClient().execute(request); entity = response.getEntity(); entityStream = entity.getContent(); logger.log(Level.SEVERE, "Can't unmarshal response from " + request.getURI() + " via " + request.getMethod() + ":" + IOUtils.toString(entityStream)); e.printStackTrace(); throw e; } finally { entity.consumeContent(); IOUtils.closeQuietly(entityStream); } } if (doRetry) { retries++; if (retries > maxRetries) { throw new HttpException("Number of retries exceeded for " + request.getURI(), error); } doRetry = false; try { Thread.sleep((int) Math.pow(2.0, retries) * 1000); } catch (InterruptedException ex) { // do nothing } } } while (!done); return result; }
From source file:com.googlecode.sardine.SardineImpl.java
/** * Small wrapper around HttpClient.execute() in order to wrap the IOException into a SardineException. *///from ww w .j a v a 2s . com private HttpResponse executeWrapper(HttpRequestBase base) throws SardineException { try { if (this.authEnabled) { Credentials creds = this.client.getCredentialsProvider().getCredentials(AuthScope.ANY); String value = "Basic " + new String(Base64.encodeBase64( new String(creds.getUserPrincipal().getName() + ":" + creds.getPassword()).getBytes())); base.setHeader("Authorization", value); } return this.client.execute(base); } catch (IOException ex) { base.abort(); throw new SardineException(ex); } }
From source file:com.keydap.sparrow.SparrowClient.java
private void setIfMatch(HttpRequestBase req, String ifMatch) { if (ifMatch != null) { req.setHeader("If-Match", ifMatch); }//ww w . j a v a 2 s . co m }