List of usage examples for org.apache.http.client.methods HttpUriRequest setHeader
void setHeader(String str, String str2);
From source file:com.louding.frame.http.download.SimpleDownloader.java
/** * /*from w ww . j a va 2s .com*/ * * @param request * @throws IOException */ private void makeRequestWithRetries(HttpUriRequest request) throws IOException { if (isResume && targetUrl != null) { File downloadFile = new File(targetUrl); long fileLen = 0; if (downloadFile.isFile() && downloadFile.exists()) { fileLen = downloadFile.length(); } if (fileLen > 0) { request.setHeader("RANGE", "bytes=" + fileLen + "-"); } } boolean retry = true; IOException cause = null; HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (retry) { try { if (!isCancelled()) { HttpResponse response = client.execute(request, context); if (!isCancelled()) { handleResponse(response); } } return; } catch (UnknownHostException e) { publishProgress(UPDATE_FAILURE, e, 0, "unknownHostExceptioncan't resolve host"); return; } catch (IOException e) { cause = e; retry = retryHandler.retryRequest(cause, ++executionCount, context); } catch (NullPointerException e) { // HttpClient 4.0.x ?bug // http://code.google.com/p/android/issues/detail?id=5255 cause = new IOException("NPE in HttpClient" + e.getMessage()); retry = retryHandler.retryRequest(cause, ++executionCount, context); } catch (Exception e) { cause = new IOException("Exception" + e.getMessage()); retry = retryHandler.retryRequest(cause, ++executionCount, context); } } if (cause != null) { throw cause; } else { throw new IOException(""); } }
From source file:com.linecorp.armeria.server.http.file.HttpFileServiceTest.java
@Test public void testFileSystemGet() throws Exception { final File barFile = new File(tmpDir, "bar.html"); final String expectedContentA = "<html/>"; final String expectedContentB = "<html><body/></html>"; Files.write(barFile.toPath(), expectedContentA.getBytes(StandardCharsets.UTF_8)); try (CloseableHttpClient hc = HttpClients.createMinimal()) { final String lastModified; HttpUriRequest req = new HttpGet(newUri("/fs/bar.html")); try (CloseableHttpResponse res = hc.execute(req)) { lastModified = assert200Ok(res, "text/html", expectedContentA); }//from www. jav a 2 s.c o m // Test if the 'If-Modified-Since' header works as expected. req = new HttpGet(newUri("/fs/bar.html")); req.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate()); try (CloseableHttpResponse res = hc.execute(req)) { assert304NotModified(res, lastModified); } // Test if the 'If-Modified-Since' header works as expected after the file is modified. req = new HttpGet(newUri("/fs/bar.html")); req.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate()); // HTTP-date has no sub-second precision; wait until the current second changes. Thread.sleep(1000); Files.write(barFile.toPath(), expectedContentB.getBytes(StandardCharsets.UTF_8)); try (CloseableHttpResponse res = hc.execute(req)) { final String newLastModified = assert200Ok(res, "text/html", expectedContentB); // Ensure that the 'Last-Modified' header did not change. assertThat(newLastModified, is(not(lastModified))); } // Test if the cache detects the file removal correctly. final boolean deleted = barFile.delete(); assertThat(deleted, is(true)); req = new HttpGet(newUri("/fs/bar.html")); req.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate()); req.setHeader(HttpHeaders.CONNECTION, "close"); try (CloseableHttpResponse res = hc.execute(req)) { assert404NotFound(res); } } }
From source file:com.klarna.checkout.BasicConnector.java
/** * Create a HttpUriRequest object.//w w w .j a va 2 s . c o m * * @param method HTTP Method * @param resource IResource implementation * @param options Options for Connector * * @return the appropriate HttpUriRequest * * @throws UnsupportedEncodingException if the payloads encoding is not * supported */ protected HttpUriRequest createRequest(final String method, final IResource resource, final ConnectorOptions options) throws UnsupportedEncodingException { URI uri = this.getUri(options, resource); HttpUriRequest req; if (method.equals("GET")) { req = new HttpGet(uri); } else { HttpPost post = new HttpPost(uri); String payload = JSONObject.toJSONString(getData(options, resource)); post.setEntity(new ByteArrayEntity(payload.getBytes("UTF-8"))); post.setHeader("Content-Type", resource.getContentType()); req = post; } req.setHeader("UserAgent", createtUserAgent().toString()); req.setHeader("Accept", resource.getContentType()); return req; }
From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java
/** * Trust a message on the client before sending, only if trust is enabled. * * @param method the method which will have headers set after the call. * @param body the body.//from w ww . ja v a2s . c o m */ public void trustMessage(HttpUriRequest method, String body) { checkActive(); if (trustEnabled) { String bodyHash = hash("request:" + method.getURI().getPath() + ":" + body); method.setHeader(HASH_HEADER, bodyHash); method.setHeader(SIG_HEADER, createTrustHeader(bodyHash)); } }
From source file:org.jets3t.service.impl.rest.httpclient.GoogleStorageService.java
@Override protected HttpUriRequest setupConnection(HTTP_METHOD method, String bucketName, String objectKey, Map<String, String> requestParameters) throws ServiceException { final HttpUriRequest request = super.setupConnection(method, bucketName, objectKey, requestParameters); // Use API version 2 if we are using OAuth2 credentials if (getProviderCredentials() instanceof OAuth2Credentials) { request.setHeader("x-goog-api-version", "2"); }//from w ww .jav a2 s . c o m return request; }
From source file:com.github.seratch.signedrequest4j.SignedRequestApacheHCImpl.java
@Override public HttpResponse doRequest(String url, HttpMethod method, RequestBody body, String charset) throws IOException { HttpClient httpClient = new DefaultHttpClient(); HttpUriRequest request = getRequest(method, url); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeoutMillis); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeoutMillis); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT); httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset); for (String name : headersToOverwrite.keySet()) { request.setHeader(name, headersToOverwrite.get(name)); }//from w w w . j a va 2 s.c o m String oAuthNonce = String.valueOf(new SecureRandom().nextLong()); Long oAuthTimestamp = System.currentTimeMillis() / 1000; String signature = getSignature(url, method, oAuthNonce, oAuthTimestamp); String authorizationHeader = getAuthorizationHeader(signature, oAuthNonce, oAuthTimestamp); request.setHeader("Authorization", authorizationHeader); if (method == HttpMethod.POST) { HttpPost postRequest = (HttpPost) request; BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(body.getBody())); entity.setContentType(body.getContentType()); postRequest.setEntity(entity); } else if (method == HttpMethod.PUT) { HttpPut putRequest = (HttpPut) request; BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(body.getBody())); entity.setContentType(body.getContentType()); putRequest.setEntity(entity); } org.apache.http.HttpResponse apacheHCResponse = httpClient.execute(request); if (apacheHCResponse.getStatusLine().getStatusCode() >= 400) { HttpResponse httpResponse = toReturnValue(apacheHCResponse, charset); throw new HttpException(apacheHCResponse.getStatusLine().getReasonPhrase(), httpResponse); } return toReturnValue(apacheHCResponse, charset); }
From source file:com.github.seratch.signedrequest4j.SignedRequestApacheHCImpl.java
/** * {@inheritDoc}//from ww w . j a va2 s. co m */ @Override public HttpResponse doRequest(String url, HttpMethod method, Map<String, Object> requestParameters, String charset) throws IOException { HttpEntity entity = null; if (method == HttpMethod.GET) { List<NameValuePair> params = toNameValuePairList(requestParameters); String queryString = URLEncodedUtils.format(params, "UTF-8"); if (queryString != null && !queryString.isEmpty()) { url = url.contains("?") ? url + "&" + queryString : url + "?" + queryString; } } else { List<NameValuePair> params = toNameValuePairList(requestParameters); entity = new UrlEncodedFormEntity(params, "UTF-8"); } // read get parameters for signature base string readQueryStringAndAddToSignatureBaseString(url); HttpClient httpClient = new DefaultHttpClient(); HttpUriRequest request = getRequest(method, url); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeoutMillis); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeoutMillis); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT); httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset); for (String name : headersToOverwrite.keySet()) { request.setHeader(name, headersToOverwrite.get(name)); } String oAuthNonce = String.valueOf(new SecureRandom().nextLong()); Long oAuthTimestamp = System.currentTimeMillis() / 1000; String signature = getSignature(url, method, oAuthNonce, oAuthTimestamp); String authorizationHeader = getAuthorizationHeader(signature, oAuthNonce, oAuthTimestamp); request.setHeader("Authorization", authorizationHeader); if (entity != null) { if (method == HttpMethod.POST) { HttpPost postRequest = (HttpPost) request; postRequest.setEntity(entity); } else if (method == HttpMethod.PUT) { HttpPut putRequest = (HttpPut) request; putRequest.setEntity(entity); } } org.apache.http.HttpResponse apacheHCResponse = httpClient.execute(request); if (apacheHCResponse.getStatusLine().getStatusCode() >= 400) { HttpResponse httpResponse = toReturnValue(apacheHCResponse, charset); throw new HttpException(apacheHCResponse.getStatusLine().getReasonPhrase(), httpResponse); } return toReturnValue(apacheHCResponse, charset); }
From source file:it.polimi.tower4clouds.rules.actions.RestCall.java
@Override public void execute(String resourceId, String value, String timestamp) { getLogger().info("Action requested. Input data: {}, {}, {}", resourceId, value, timestamp); try {//from w w w . ja va 2s. co m CloseableHttpClient client = HttpClients.createDefault(); HttpUriRequest request; String url = getParameters().get(URL); String method = getParameters().get(METHOD).toUpperCase(); switch (method) { case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; case DELETE: request = new HttpDelete(url); break; case GET: request = new HttpGet(url); break; default: getLogger().error("Unknown method {}", method); return; } request.setHeader("Cache-Control", "no-cache"); CloseableHttpResponse response = client.execute(request); getLogger().info("Rest call executed"); response.close(); } catch (Exception e) { getLogger().error("Error executing rest call", e); } }
From source file:org.fcrepo.test.api.TestAdminAPI.java
private HttpResponse getOrDelete(String method, boolean authenticate) throws Exception { if (url == null || url.length() == 0) { throw new IllegalArgumentException("url must be a non-empty value"); } else if (!(url.startsWith("http://") || url.startsWith("https://"))) { url = getBaseURL() + url;/*w w w. j a va2s .c o m*/ } HttpUriRequest httpMethod = null; if (method.equals("GET")) { httpMethod = new HttpGet(url); } else if (method.equals("DELETE")) { httpMethod = new HttpDelete(url); } else { throw new IllegalArgumentException("method must be one of GET or DELETE."); } httpMethod.setHeader(HttpHeaders.CONNECTION, "Keep-Alive"); return getClient(authenticate).execute(httpMethod); }