List of usage examples for org.apache.http.client.methods HttpRequestBase setHeader
public void setHeader(String str, String str2)
From source file:de.jetwick.snacktory.HtmlFetcher.java
protected CloseableHttpResponse createUrlConnection(String urlAsStr, int timeout, boolean includeSomeGooseOptions, boolean isHead) throws MalformedURLException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpRequestBase request = null; if (isHead) { request = new HttpHead(urlAsStr); } else {//from w ww.j a va2 s .c o m request = new HttpGet(urlAsStr); } RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout) .setConnectTimeout(timeout).setSocketTimeout(timeout).setCookieSpec(CookieSpecs.STANDARD).build(); request.setHeader("User-Agent", userAgent); request.setHeader("Accept", accept); if (includeSomeGooseOptions) { request.setHeader("Accept-Language", language); request.setHeader("content-charset", charset); request.setHeader("Referer", referrer); // avoid the cache for testing purposes only? request.setHeader("Cache-Control", cacheControl); } // suggest respond to be gzipped or deflated (which is just another compression) // http://stackoverflow.com/q/3932117 request.setHeader("Accept-Encoding", "gzip, deflate"); request.setConfig(requestConfig); return httpclient.execute(request); }
From source file:com.mollie.api.MollieClient.java
/** * Perform a http call. This method is used by the resource specific classes. * Please use the payments() method to perform operations on payments. * * @param method the http method to use//from www. ja v a 2s .c om * @param apiMethod the api method to call * @param httpBody the contents to send to the server. * @return result of the http call * @throws MollieException when the api key is not set or when there is a * problem communicating with the mollie server. * @see #performHttpCall(String method, String apiMethod) */ public String performHttpCall(String method, String apiMethod, String httpBody) throws MollieException { URI uri = null; String result = null; if (_apiKey == null || _apiKey.trim().equals("")) { throw new MollieException("You have not set an api key. Please use setApiKey() to set the API key."); } try { URIBuilder ub = new URIBuilder(this._apiEndpoint + "/" + API_VERSION + "/" + apiMethod); uri = ub.build(); } catch (URISyntaxException e) { e.printStackTrace(); } if (uri != null) { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpRequestBase action = null; HttpResponse response = null; if (method.equals(HTTP_POST)) { action = new HttpPost(uri); } else if (method.equals(HTTP_DELETE)) { action = new HttpDelete(uri); } else { action = new HttpGet(uri); } if (httpBody != null && action instanceof HttpPost) { StringEntity entity = new StringEntity(httpBody, ContentType.APPLICATION_JSON); ((HttpPost) action).setEntity(entity); } action.setHeader("Authorization", "Bearer " + this._apiKey); action.setHeader("Accept", ContentType.APPLICATION_JSON.getMimeType()); try { response = httpclient.execute(action); HttpEntity entity = response.getEntity(); StringWriter sw = new StringWriter(); IOUtils.copy(entity.getContent(), sw, "UTF-8"); result = sw.toString(); EntityUtils.consume(entity); } catch (Exception e) { throw new MollieException("Unable to communicate with Mollie"); } try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
From source file:org.apache.hive.jdbc.TestActivePassiveHA.java
private void setupAuthHeaders(final HttpRequestBase method) { String authB64Code = B64Code.encode(ADMIN_USER + ":" + ADMIN_PASSWORD, StringUtil.__ISO_8859_1); method.setHeader(HttpHeader.AUTHORIZATION.asString(), "Basic " + authB64Code); }
From source file:com.mikecorrigan.bohrium.pubsub.Transaction.java
private int read(HttpRequestBase request) { Log.v(TAG, "read"); CookieStore mCookieStore = new BasicCookieStore(); mCookieStore.addCookie(mAuthCookie); DefaultHttpClient httpClient = new DefaultHttpClient(); BasicHttpContext mHttpContext = new BasicHttpContext(); mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore); try {// ww w. j a v a 2s . co m final HttpParams getParams = new BasicHttpParams(); HttpClientParams.setRedirecting(getParams, false); request.setParams(getParams); request.setHeader("Accept", getMimeType()); HttpResponse response = httpClient.execute(request, mHttpContext); Log.d(TAG, "status=" + response.getStatusLine()); // Read response body. HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { InputStream is = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } is.close(); mStatusCode = response.getStatusLine().getStatusCode(); mStatusReason = response.getStatusLine().getReasonPhrase(); if (mStatusCode == 200) { mResponseBody = decode(sb.toString()); Log.v(TAG, "mResponseBody=" + sb.toString()); } return mStatusCode; } } catch (IOException e) { Log.e(TAG, "exception=" + e); Log.e(TAG, Log.getStackTraceString(e)); } finally { httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); } return mStatusCode; }
From source file:com.seleritycorp.common.base.http.client.HttpRequest.java
private org.apache.http.HttpResponse getHttpResponse() throws HttpException { final HttpRequestBase request; switch (method) { case HttpGet.METHOD_NAME: request = new HttpGet(); break;//www . ja v a2s. c o m case HttpPost.METHOD_NAME: request = new HttpPost(); break; default: throw new HttpException("Unknown HTTP method '" + method + "'"); } try { request.setURI(URI.create(uri)); } catch (IllegalArgumentException e) { throw new HttpException("Failed to create URI '" + uri + "'", e); } if (userAgent != null) { request.setHeader(HTTP.USER_AGENT, userAgent); } if (readTimeoutMillis >= 0) { request.setConfig(RequestConfig.custom().setSocketTimeout(readTimeoutMillis) .setConnectTimeout(readTimeoutMillis).setConnectionRequestTimeout(readTimeoutMillis).build()); } if (!data.isEmpty()) { if (request instanceof HttpEntityEnclosingRequestBase) { final HttpEntity entity; ContentType localContentType = contentType; if (localContentType == null) { localContentType = ContentType.create("text/plain", StandardCharsets.UTF_8); } entity = new StringEntity(data, localContentType); HttpEntityEnclosingRequestBase entityRequest = (HttpEntityEnclosingRequestBase) request; entityRequest.setEntity(entity); } else { throw new HttpException( "Request " + request.getMethod() + " does not allow to send data " + "with the request"); } } final HttpClient httpClient; if (uri.startsWith("file://")) { httpClient = this.fileHttpClient; } else { httpClient = this.netHttpClient; } final org.apache.http.HttpResponse response; try { response = httpClient.execute(request); } catch (IOException e) { throw new HttpException("Failed to execute request to '" + uri + "'", e); } return response; }
From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java
private void setHttpHeaders(HttpRequestBase requestBase, Map<String, String> header) { if (header != null && !header.isEmpty()) { Set<String> keys = header.keySet(); Iterator<String> it = keys.iterator(); while (it.hasNext()) { String key = it.next(); String value = header.get(key); if (requestBase != null) { requestBase.setHeader(key, value); }/*from www . jav a 2 s .c o m*/ } } if (!requestBase.containsHeader("Content-type")) { requestBase.setHeader("Content-type", "application/json"); } if (!requestBase.containsHeader("Host")) { requestBase.setHeader("Host", host + ":" + port); } if (!requestBase.containsHeader("Accept")) { requestBase.setHeader("Accept", "application/json"); } }
From source file:com.sap.core.odata.fit.ref.AbstractRefTest.java
protected HttpResponse callUri(final ODataHttpMethod httpMethod, final String uri, final String additionalHeader, final String additionalHeaderValue, final String requestBody, final String requestContentType, final HttpStatusCodes expectedStatusCode) throws Exception { HttpRequestBase request = httpMethod == ODataHttpMethod.GET ? new HttpGet() : httpMethod == ODataHttpMethod.DELETE ? new HttpDelete() : httpMethod == ODataHttpMethod.POST ? new HttpPost() : httpMethod == ODataHttpMethod.PUT ? new HttpPut() : new HttpPatch(); request.setURI(URI.create(getEndpoint() + uri)); if (additionalHeader != null) { request.addHeader(additionalHeader, additionalHeaderValue); }//from ww w . j ava 2 s . c o m if (requestBody != null) { ((HttpEntityEnclosingRequest) request).setEntity(new StringEntity(requestBody)); request.setHeader(HttpHeaders.CONTENT_TYPE, requestContentType); } final HttpResponse response = getHttpClient().execute(request); assertNotNull(response); assertEquals(expectedStatusCode.getStatusCode(), response.getStatusLine().getStatusCode()); if (expectedStatusCode == HttpStatusCodes.OK) { assertNotNull(response.getEntity()); assertNotNull(response.getEntity().getContent()); } else if (expectedStatusCode == HttpStatusCodes.CREATED) { assertNotNull(response.getEntity()); assertNotNull(response.getEntity().getContent()); assertNotNull(response.getFirstHeader(HttpHeaders.LOCATION)); } else if (expectedStatusCode == HttpStatusCodes.NO_CONTENT) { assertTrue(response.getEntity() == null || response.getEntity().getContent() == null); } return response; }
From source file:org.apache.jmeter.protocol.http.control.CacheManager.java
/** * Check the cache, and if there is a match, set the headers: * <ul>/*w ww .ja v a2 s.c o m*/ * <li>If-Modified-Since</li> * <li>If-None-Match</li> * </ul> * Apache HttpClient version. * @param url {@link URL} to look up in cache * @param request where to set the headers */ public void setHeaders(URL url, HttpRequestBase request) { CacheEntry entry = getCache().get(url.toString()); if (log.isDebugEnabled()) { log.debug(request.getMethod() + "(OAH) " + url.toString() + " " + entry); } if (entry != null) { final String lastModified = entry.getLastModified(); if (lastModified != null) { request.setHeader(HTTPConstants.IF_MODIFIED_SINCE, lastModified); } final String etag = entry.getEtag(); if (etag != null) { request.setHeader(HTTPConstants.IF_NONE_MATCH, etag); } } }
From source file:com.hp.saas.agm.rest.client.AliRestClient.java
private void setHeaders(HttpRequestBase method, Map<String, String> headers) { for (Map.Entry<String, String> entry : headers.entrySet()) { method.setHeader(entry.getKey(), entry.getValue()); }/*w ww .ja v a2 s . c om*/ }