List of usage examples for org.apache.http.client.methods HttpRequestBase setHeader
public void setHeader(String str, String str2)
From source file:de.escidoc.core.common.util.service.ConnectionUtility.java
/** * //from w ww .ja va2s .com * @param request * @param cookie * @return The response of the request. * @throws WebserverSystemException */ private HttpResponse executeRequest(final DefaultHttpClient client, final HttpRequestBase request, final URL url, final Cookie cookie, final String username, final String password) throws WebserverSystemException { try { request.setURI(url.toURI()); if (cookie != null) { HttpClientParams.setCookiePolicy(request.getParams(), CookiePolicy.BEST_MATCH); request.setHeader("Cookie", cookie.getName() + '=' + cookie.getValue()); } final DefaultHttpClient clientToUse = client == null ? getHttpClient() : client; if (PROXY_HOST != null && isProxyRequired(url)) { clientToUse.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, PROXY_HOST); } if (username != null && password != null) { setAuthentication(clientToUse, url, username, password); } final HttpResponse httpResponse = clientToUse.execute(request); final int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode / HTTP_RESPONSE_CLASS != HttpServletResponse.SC_OK / HTTP_RESPONSE_CLASS) { final String errorPage = readResponse(httpResponse); throw new WebserverSystemException( "HTTP connection to \"" + request.getURI().toString() + "\" failed: " + errorPage); } return httpResponse; } catch (final IOException e) { throw new WebserverSystemException(e); } catch (final URISyntaxException e) { throw new WebserverSystemException("Illegal URL '" + url + "'.", e); } }
From source file:org.keycloak.broker.provider.util.SimpleHttp.java
private Response makeRequest() throws IOException { boolean get = method.equals("GET"); boolean post = method.equals("POST"); boolean delete = method.equals("DELETE"); HttpRequestBase httpRequest = new HttpPost(url); if (get) {// w w w . j av a 2 s .com httpRequest = new HttpGet(appendParameterToUrl(url)); } if (delete) { httpRequest = new HttpDelete(appendParameterToUrl(url)); } if (post) { if (params != null) { ((HttpPost) httpRequest).setEntity(getFormEntityFromParameter()); } else if (entity != null) { if (headers == null || !headers.containsKey("Content-Type")) { header("Content-Type", "application/json"); } ((HttpPost) httpRequest).setEntity(getJsonEntity()); } else { throw new IllegalStateException("No content set"); } } if (headers != null) { for (Map.Entry<String, String> h : headers.entrySet()) { httpRequest.setHeader(h.getKey(), h.getValue()); } } return new Response(client.execute(httpRequest)); }
From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.AbstractApacheClientHttpInvoker.java
protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers, final Output writer, final BindingSession session, BigInteger offset, BigInteger length) { int respCode = -1; try {/*from ww w . j av a 2 s . com*/ // log before connect if (LOG.isDebugEnabled()) { LOG.debug("Session {}: {} {}", session.getSessionId(), method, url); } // get HTTP client object from session DefaultHttpClient httpclient = (DefaultHttpClient) session.get(HTTP_CLIENT); if (httpclient == null) { session.writeLock(); try { httpclient = (DefaultHttpClient) session.get(HTTP_CLIENT); if (httpclient == null) { httpclient = createHttpClient(url, session); session.put(HTTP_CLIENT, httpclient, true); } } finally { session.writeUnlock(); } } HttpRequestBase request = null; if ("GET".equals(method)) { request = new HttpGet(url.toString()); } else if ("POST".equals(method)) { request = new HttpPost(url.toString()); } else if ("PUT".equals(method)) { request = new HttpPut(url.toString()); } else if ("DELETE".equals(method)) { request = new HttpDelete(url.toString()); } else { throw new CmisRuntimeException("Invalid HTTP method!"); } // set content type if (contentType != null) { request.setHeader("Content-Type", contentType); } // set other headers if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { request.addHeader(header.getKey(), header.getValue()); } } // authenticate AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session); if (authProvider != null) { Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString()); if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getKey() != null && isNotEmpty(header.getValue())) { String key = header.getKey(); if (key.equalsIgnoreCase("user-agent")) { request.setHeader("User-Agent", header.getValue().get(0)); } else { for (String value : header.getValue()) { if (value != null) { request.addHeader(key, value); } } } } } } } // range if ((offset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((offset == null) || (offset.signum() == -1)) { offset = BigInteger.ZERO; } sb.append(offset.toString()); sb.append('-'); if ((length != null) && (length.signum() == 1)) { sb.append(offset.add(length.subtract(BigInteger.ONE)).toString()); } request.setHeader("Range", sb.toString()); } // compression Object compression = session.get(SessionParameter.COMPRESSION); if ((compression != null) && Boolean.parseBoolean(compression.toString())) { request.setHeader("Accept-Encoding", "gzip,deflate"); } // locale if (session.get(CmisBindingsHelper.ACCEPT_LANGUAGE) instanceof String) { request.setHeader("Accept-Language", session.get(CmisBindingsHelper.ACCEPT_LANGUAGE).toString()); } // send data if (writer != null) { Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION); final boolean clientCompressionFlag = (clientCompression != null) && Boolean.parseBoolean(clientCompression.toString()); if (clientCompressionFlag) { request.setHeader("Content-Encoding", "gzip"); } AbstractHttpEntity streamEntity = new AbstractHttpEntity() { @Override public boolean isChunked() { return true; } @Override public boolean isRepeatable() { return false; } @Override public long getContentLength() { return -1; } @Override public boolean isStreaming() { return false; } @Override public InputStream getContent() throws IOException { throw new UnsupportedOperationException(); } @Override public void writeTo(final OutputStream outstream) throws IOException { OutputStream connOut = null; if (clientCompressionFlag) { connOut = new GZIPOutputStream(outstream, 4096); } else { connOut = outstream; } OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); try { writer.write(out); } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new IOException(e); } out.flush(); if (connOut instanceof GZIPOutputStream) { ((GZIPOutputStream) connOut).finish(); } } }; ((HttpEntityEnclosingRequestBase) request).setEntity(streamEntity); } // connect HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); // get stream, if present respCode = response.getStatusLine().getStatusCode(); InputStream inputStream = null; InputStream errorStream = null; if ((respCode == 200) || (respCode == 201) || (respCode == 203) || (respCode == 206)) { if (entity != null) { inputStream = entity.getContent(); } else { inputStream = new ByteArrayInputStream(new byte[0]); } } else { if (entity != null) { errorStream = entity.getContent(); } else { errorStream = new ByteArrayInputStream(new byte[0]); } } // collect headers Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>(); for (Header header : response.getAllHeaders()) { List<String> values = responseHeaders.get(header.getName()); if (values == null) { values = new ArrayList<String>(); responseHeaders.put(header.getName(), values); } values.add(header.getValue()); } // log after connect if (LOG.isTraceEnabled()) { LOG.trace("Session {}: {} {} > Headers: {}", session.getSessionId(), method, url, responseHeaders.toString()); } // forward response HTTP headers if (authProvider != null) { authProvider.putResponseHeaders(url.toString(), respCode, responseHeaders); } // get the response return new Response(respCode, response.getStatusLine().getReasonPhrase(), responseHeaders, inputStream, errorStream); } catch (Exception e) { String status = (respCode > 0 ? " (HTTP status code " + respCode + ")" : ""); throw new CmisConnectionException("Cannot access \"" + url + "\"" + status + ": " + e.getMessage(), e); } }
From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java
public HttpResponse execute(HttpRequest request) throws IOException { URI uri = createURI(request); HttpRequestBase internalRequest; if (request.method == HttpMethod.HEAD) { internalRequest = new HttpHead(uri); } else {// ww w . j ava2s . c om HttpMethodWithEntity methodWithEntity = new HttpMethodWithEntity(uri, request.method.name()); if (request.hasBody()) { ByteArrayEntity entity = new ByteArrayEntity(request.body.getBytes(StandardCharsets.UTF_8)); String contentType = request.headers().get(HttpHeaders.CONTENT_TYPE); if (Strings.hasLength(contentType)) { entity.setContentType(contentType); } else { entity.setContentType(ContentType.TEXT_PLAIN.toString()); } methodWithEntity.setEntity(entity); } internalRequest = methodWithEntity; } internalRequest.setHeader(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name()); // headers if (request.headers().isEmpty() == false) { for (Map.Entry<String, String> entry : request.headers.entrySet()) { internalRequest.setHeader(entry.getKey(), entry.getValue()); } } // BWC - hack for input requests made to elasticsearch that do not provide the right content-type header! if (request.hasBody() && internalRequest.containsHeader("Content-Type") == false) { XContentType xContentType = XContentFactory.xContentType(request.body()); if (xContentType != null) { internalRequest.setHeader("Content-Type", xContentType.mediaType()); } } RequestConfig.Builder config = RequestConfig.custom(); setProxy(config, request, settingsProxy); HttpClientContext localContext = HttpClientContext.create(); // auth if (request.auth() != null) { ApplicableHttpAuth applicableAuth = httpAuthRegistry.createApplicable(request.auth); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); applicableAuth.apply(credentialsProvider, new AuthScope(request.host, request.port)); localContext.setCredentialsProvider(credentialsProvider); // preemptive auth, no need to wait for a 401 first AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(new HttpHost(request.host, request.port, request.scheme.scheme()), basicAuth); localContext.setAuthCache(authCache); } // timeouts if (request.connectionTimeout() != null) { config.setConnectTimeout(Math.toIntExact(request.connectionTimeout.millis())); } else { config.setConnectTimeout(Math.toIntExact(defaultConnectionTimeout.millis())); } if (request.readTimeout() != null) { config.setSocketTimeout(Math.toIntExact(request.readTimeout.millis())); config.setConnectionRequestTimeout(Math.toIntExact(request.readTimeout.millis())); } else { config.setSocketTimeout(Math.toIntExact(defaultReadTimeout.millis())); config.setConnectionRequestTimeout(Math.toIntExact(defaultReadTimeout.millis())); } internalRequest.setConfig(config.build()); try (CloseableHttpResponse response = SocketAccess .doPrivileged(() -> client.execute(internalRequest, localContext))) { // headers Header[] headers = response.getAllHeaders(); Map<String, String[]> responseHeaders = new HashMap<>(headers.length); for (Header header : headers) { if (responseHeaders.containsKey(header.getName())) { String[] old = responseHeaders.get(header.getName()); String[] values = new String[old.length + 1]; System.arraycopy(old, 0, values, 0, old.length); values[values.length - 1] = header.getValue(); responseHeaders.put(header.getName(), values); } else { responseHeaders.put(header.getName(), new String[] { header.getValue() }); } } final byte[] body; // not every response has a content, i.e. 204 if (response.getEntity() == null) { body = new byte[0]; } else { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { try (InputStream is = new SizeLimitInputStream(maxResponseSize, response.getEntity().getContent())) { Streams.copy(is, outputStream); } body = outputStream.toByteArray(); } } return new HttpResponse(response.getStatusLine().getStatusCode(), body, responseHeaders); } }
From source file:org.apache.tomcat.maven.common.deployer.TomcatManager.java
/** * Invokes Tomcat manager with the specified command and content data. * * @param path the Tomcat manager command to invoke * @param data file to deploy/*from w w w . j av a 2s . c om*/ * @return the Tomcat manager response * @throws TomcatManagerException if the Tomcat manager request fails * @throws IOException if an i/o error occurs */ protected TomcatManagerResponse invoke(String path, File data, long length) throws TomcatManagerException, IOException { HttpRequestBase httpRequestBase = null; if (data == null) { httpRequestBase = new HttpGet(url + path); } else { HttpPut httpPut = new HttpPut(url + path); httpPut.setEntity(new RequestEntityImplementation(data, length, url + path, verbose)); httpRequestBase = httpPut; } if (userAgent != null) { httpRequestBase.setHeader("User-Agent", userAgent); } HttpResponse response = httpClient.execute(httpRequestBase, localContext); int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { // Success Codes case HttpStatus.SC_OK: // 200 case HttpStatus.SC_CREATED: // 201 case HttpStatus.SC_ACCEPTED: // 202 break; // handle all redirect even if http specs says " the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user" case HttpStatus.SC_MOVED_PERMANENTLY: // 301 case HttpStatus.SC_MOVED_TEMPORARILY: // 302 case HttpStatus.SC_SEE_OTHER: // 303 String relocateUrl = calculateRelocatedUrl(response); this.url = new URL(relocateUrl); return invoke(path, data, length); } return new TomcatManagerResponse().setStatusCode(response.getStatusLine().getStatusCode()) .setReasonPhrase(response.getStatusLine().getReasonPhrase()) .setHttpResponseBody(IOUtils.toString(response.getEntity().getContent())); }
From source file:com.epam.ngb.cli.manager.command.handler.http.AbstractHTTPCommandHandler.java
/** * Sends request to NGB server, retrieves an authorization token and adds it to an input request. * This is required for secure requests. * @param request to authorize/*from ww w .j a va 2s .co m*/ */ protected void addAuthorizationToRequest(HttpRequestBase request) { try { HttpPost post = new HttpPost(serverParameters.getServerUrl() + serverParameters.getAuthenticationUrl()); StringEntity input = new StringEntity(serverParameters.getAuthPayload()); input.setContentType(APPLICATION_JSON); post.setEntity(input); post.setHeader(CACHE_CONTROL, CACHE_CONTROL_NO_CACHE); post.setHeader(CONTENT_TYPE, "application/x-www-form-urlencoded"); String result = RequestManager.executeRequest(post); Authentication authentication = getMapper().readValue(result, Authentication.class); request.setHeader("authorization", "Bearer " + authentication.getAccessToken()); } catch (IOException e) { throw new ApplicationException("Failed to authenticate request", e); } }
From source file:com.algolia.search.saas.APIClient.java
private JSONObject _requestByHost(HttpRequestBase req, String host, String url, String json, HashMap<String, String> errors) throws AlgoliaException { req.reset();/*w ww. j a v a 2 s .co m*/ // set URL try { req.setURI(new URI("https://" + host + url)); } catch (URISyntaxException e) { // never reached throw new IllegalStateException(e); } // set auth headers req.setHeader("X-Algolia-Application-Id", this.applicationID); if (forwardAdminAPIKey == null) { req.setHeader("X-Algolia-API-Key", this.apiKey); } else { req.setHeader("X-Algolia-API-Key", this.forwardAdminAPIKey); req.setHeader("X-Forwarded-For", this.forwardEndUserIP); req.setHeader("X-Forwarded-API-Key", this.forwardRateLimitAPIKey); } for (Entry<String, String> entry : headers.entrySet()) { req.setHeader(entry.getKey(), entry.getValue()); } // set user agent req.setHeader("User-Agent", "Algolia for Java " + version); // set JSON entity if (json != null) { if (!(req instanceof HttpEntityEnclosingRequestBase)) { throw new IllegalArgumentException("Method " + req.getMethod() + " cannot enclose entity"); } req.setHeader("Content-type", "application/json"); try { StringEntity se = new StringEntity(json, "UTF-8"); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); ((HttpEntityEnclosingRequestBase) req).setEntity(se); } catch (UnsupportedEncodingException e) { throw new AlgoliaException("Invalid JSON Object: " + json); // $COVERAGE-IGNORE$ } } RequestConfig config = RequestConfig.custom().setSocketTimeout(httpSocketTimeoutMS) .setConnectTimeout(httpConnectTimeoutMS).setConnectionRequestTimeout(httpConnectTimeoutMS).build(); req.setConfig(config); HttpResponse response; try { response = httpClient.execute(req); } catch (IOException e) { // on error continue on the next host errors.put(host, String.format("%s=%s", e.getClass().getName(), e.getMessage())); return null; } try { int code = response.getStatusLine().getStatusCode(); if (code / 100 == 4) { String message = ""; try { message = EntityUtils.toString(response.getEntity()); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (code == 400) { throw new AlgoliaException(code, message.length() > 0 ? message : "Bad request"); } else if (code == 403) { throw new AlgoliaException(code, message.length() > 0 ? message : "Invalid Application-ID or API-Key"); } else if (code == 404) { throw new AlgoliaException(code, message.length() > 0 ? message : "Resource does not exist"); } else { throw new AlgoliaException(code, message.length() > 0 ? message : "Error"); } } if (code / 100 != 2) { try { errors.put(host, EntityUtils.toString(response.getEntity())); } catch (IOException e) { errors.put(host, String.valueOf(code)); } // KO, continue return null; } try { InputStream istream = response.getEntity().getContent(); InputStreamReader is = new InputStreamReader(istream, "UTF-8"); JSONTokener tokener = new JSONTokener(is); JSONObject res = new JSONObject(tokener); is.close(); return res; } catch (IOException e) { return null; } catch (JSONException e) { throw new AlgoliaException("JSON decode error:" + e.getMessage()); } } finally { req.releaseConnection(); } }
From source file:com.tripit.auth.OAuthCredential.java
public void authorize(HttpRequestBase request) throws Exception { OAuthConsumer consumer = new CommonsHttpOAuthConsumer(this.consumerKey, this.consumerSecret); consumer.setMessageSigner(new HmacSha1MessageSigner()); if (this.userKey != null && this.userSecret != null) { consumer.setTokenWithSecret(this.userKey, this.userSecret); }//from w w w . j a va 2 s .c o m if (this.requestorId != null) { HttpParameters params = new HttpParameters(); params.put("xoauth_requestor_id", OAuth.percentEncode(this.requestorId)); consumer.setAdditionalParameters(params); consumer.setSigningStrategy(new AuthorizationHeaderSigningStrategy() { private static final long serialVersionUID = 1L; public String writeSignature(String signature, HttpRequest request, HttpParameters parameters) { String header = super.writeSignature(signature, request, parameters) + ", " + parameters.getAsHeaderElement("xoauth_requestor_id"); request.setHeader(OAuth.HTTP_AUTHORIZATION_HEADER, header); return header; } }); } consumer.sign(request); }
From source file:playn.http.HttpAndroid.java
@Override protected void doSend(final HttpRequest request, final Callback<HttpResponse> callback) { platform.invokeAsync(new Runnable() { public void run() { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setHttpElementCharset(params, HTTP.UTF_8); HttpClient httpclient = new DefaultHttpClient(params); HttpRequestBase req; HttpMethod method = request.getMethod(); String url = request.getUrl(); switch (method) { case GET: req = new HttpGet(url); break; case POST: req = new HttpPost(url); break; case PUT: req = new HttpPut(url); break; default: throw new UnsupportedOperationException(method.toString()); }//from w w w. ja v a2 s .c o m String requestBody = request.getBody(); if (requestBody != null && req instanceof HttpEntityEnclosingRequestBase) { try { HttpEntityEnclosingRequestBase op = (HttpEntityEnclosingRequestBase) req; op.setEntity(new StringEntity(requestBody)); } catch (UnsupportedEncodingException e) { platform.notifyFailure(callback, e); } } for (Map.Entry<String, String> header : request.getHeaders()) { req.setHeader(header.getKey(), header.getValue()); } int statusCode = -1; String statusLineMessage = null; Map<String, String> responseHeaders = new HashMap<String, String>(); String responseBody = null; try { org.apache.http.HttpResponse response = httpclient.execute(req); StatusLine statusLine = response.getStatusLine(); statusCode = statusLine.getStatusCode(); statusLineMessage = statusLine.getReasonPhrase(); for (Header header : response.getAllHeaders()) { responseHeaders.put(header.getName(), header.getValue()); } responseBody = EntityUtils.toString(response.getEntity()); HttpResponse httpResponse = new HttpResponse(statusCode, statusLineMessage, responseHeaders, responseBody); platform.notifySuccess(callback, httpResponse); } catch (Throwable cause) { HttpErrorType errorType = cause instanceof ConnectTimeoutException || cause instanceof HttpHostConnectException || cause instanceof ConnectionPoolTimeoutException || cause instanceof UnknownHostException ? HttpErrorType.NETWORK_FAILURE : HttpErrorType.SERVER_ERROR; HttpException reason = new HttpException(statusCode, statusLineMessage, responseBody, cause, errorType); platform.notifyFailure(callback, reason); } } }); }
From source file:com.triarc.sync.SyncAdapter.java
private HttpRequestBase createRequest(SyncTypeCollection typeCollection, String password, String path, MutableBoolean hasChanges) throws Exception, IOException, UnsupportedEncodingException { String localTableName = typeCollection.getName(); Log.i(TAG, "Streaming data for type: " + localTableName); String actionPath = path + "/" + typeCollection.getController() + "/" + typeCollection.getAction(); HttpRequestBase request; HttpPost httppost = new HttpPost(actionPath); request = httppost;// www . j av a2 s. c o m JSONObject entity; try { entity = this.getVersionSets(typeCollection, hasChanges); } finally { if (hasChanges.getValue()) { // keep the ui locked until the change is confirmed from the // server hasChanges.setValue(true); this.lockUi(typeCollection); } } httppost.setEntity(new StringEntity(entity.toString(), HTTP.UTF_8)); request.setHeader("Content-Type", "application/json; charset=utf-8"); request.addHeader("Cookie", password); return request; }