List of usage examples for org.apache.http.client.methods HttpRequestBase addHeader
public void addHeader(Header header)
From source file:com.tealeaf.util.HTTP.java
public Response makeRequest(Methods method, URI uri, HashMap<String, String> requestHeaders, String data) { HttpRequestBase request = null; try {//w ww. jav a2 s.c o m if (method == Methods.GET) { request = new HttpGet(); } else if (method == Methods.POST) { request = new HttpPost(); if (data != null) { ((HttpPost) request).setEntity(new StringEntity(data, "UTF-8")); } } else if (method == Methods.PUT) { request = new HttpPut(); if (data != null) { ((HttpPut) request).setEntity(new StringEntity(data, "UTF-8")); } } else if (method == Methods.DELETE) { request = new HttpDelete(); } else if (method == Methods.HEAD) { request = new HttpHead(); } } catch (UnsupportedEncodingException e) { logger.log(e); } request.setURI(uri); AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent); if (requestHeaders != null) { for (Map.Entry<String, String> entry : requestHeaders.entrySet()) { request.addHeader(new BasicHeader(entry.getKey(), entry.getValue())); } } HttpResponse response = null; Response retVal = new Response(); retVal.headers = new HashMap<String, String>(); try { response = client.execute(request, localContext); } catch (SocketTimeoutException e) { // forget it--we don't care that the user couldn't connect // TODO hand this back as an error to JS } catch (IOException e) { if (!caughtIOException) { caughtIOException = true; logger.log(e); } } catch (Exception e) { logger.log(e); } if (response != null) { retVal.status = response.getStatusLine().getStatusCode(); retVal.body = readContent(response); for (Header header : response.getAllHeaders()) { retVal.headers.put(header.getName(), header.getValue()); } } client.close(); return retVal; }
From source file:org.coding.git.api.CodingNetConnection.java
@NotNull private CloseableHttpResponse doREST(@NotNull final String uri, @Nullable final String requestBody, @NotNull final Collection<Header> headers, @NotNull final HttpVerb verb) throws IOException { HttpRequestBase request; switch (verb) { case POST://from w ww .j a v a2 s .c o m request = new HttpPost(uri); if (requestBody != null) { ((HttpPost) request).setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); } break; case PATCH: request = new HttpPatch(uri); if (requestBody != null) { ((HttpPatch) request).setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON)); } break; case GET: request = new HttpGet(uri); break; case DELETE: request = new HttpDelete(uri); break; case HEAD: request = new HttpHead(uri); break; default: throw new IllegalStateException("Unknown HttpVerb: " + verb.toString()); } for (Header header : headers) { request.addHeader(header); } myRequest = request; return myClient.execute(request); }
From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPSenderImpl.java
public void addCustomHeaders(HttpRequestBase method, MessageContext msgContext) { boolean isCustomUserAgentSet = false; // set the custom headers, if available Object httpHeadersObj = msgContext.getProperty(HTTPConstants.HTTP_HEADERS); if (httpHeadersObj != null) { if (httpHeadersObj instanceof List) { List httpHeaders = (List) httpHeadersObj; for (int i = 0; i < httpHeaders.size(); i++) { NamedValue nv = (NamedValue) httpHeaders.get(i); if (nv != null) { Header header = new BasicHeader(nv.getName(), nv.getValue()); if (HTTPConstants.HEADER_USER_AGENT.equals(header.getName())) { isCustomUserAgentSet = true; }//from w w w. j a v a 2s. c o m method.addHeader(header); } } } if (httpHeadersObj instanceof Map) { Map httpHeaders = (Map) httpHeadersObj; for (Iterator iterator = httpHeaders.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); if (HTTPConstants.HEADER_USER_AGENT.equals(key)) { isCustomUserAgentSet = true; } method.addHeader(key, value); } } } // we have to consider the TRANSPORT_HEADERS map as well Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); if (transportHeaders != null) { removeUnwantedHeaders(msgContext); Set headerEntries = transportHeaders.entrySet(); for (Object headerEntry : headerEntries) { if (headerEntry instanceof Map.Entry) { Header[] headers = method.getAllHeaders(); boolean headerAdded = false; for (Header header : headers) { if (header.getName() != null && header.getName().equals(((Map.Entry) headerEntry).getKey())) { headerAdded = true; break; } } if (!headerAdded) { method.addHeader(((Map.Entry) headerEntry).getKey().toString(), ((Map.Entry) headerEntry).getValue().toString()); } } } } if (!isCustomUserAgentSet) { String userAgentString = getUserAgent(msgContext); method.setHeader(HTTPConstants.HEADER_USER_AGENT, userAgentString); } }
From source file:org.fao.geonet.api.mapservers.GeoServerRest.java
/** * @param method e.g. 'POST', 'GET', 'PUT' or 'DELETE' * @param urlParams REST API parameter * @param postData XML data/*from ww w . ja v a 2 s .c o m*/ * @param file File to upload * @param contentType type of content in case of post data or file updload. */ public @CheckReturnValue int sendREST(String method, String urlParams, String postData, Path file, String contentType, Boolean saveResponse) throws IOException { response = ""; String url = this.restUrl + urlParams; if (Log.isDebugEnabled(LOGGER_NAME)) { Log.debug(LOGGER_NAME, "url:" + url); Log.debug(LOGGER_NAME, "method:" + method); if (postData != null) Log.debug(LOGGER_NAME, "postData:" + postData); } HttpRequestBase m; if (method.equals(METHOD_PUT)) { m = new HttpPut(url); if (file != null) { ((HttpPut) m) .setEntity(new PathHttpEntity(file, ContentType.create(contentType, Constants.ENCODING))); } if (postData != null) { final StringEntity entity = new StringEntity(postData, ContentType.create(contentType, Constants.ENCODING)); ((HttpPut) m).setEntity(entity); } } else if (method.equals(METHOD_DELETE)) { m = new HttpDelete(url); } else if (method.equals(METHOD_POST)) { m = new HttpPost(url); if (postData != null) { final StringEntity entity = new StringEntity(postData, ContentType.create(contentType, Constants.ENCODING)); ((HttpPost) m).setEntity(entity); } } else { m = new HttpGet(url); } if (contentType != null && !"".equals(contentType)) { m.setHeader("Content-type", contentType); } m.setConfig(RequestConfig.custom().setAuthenticationEnabled(true).build()); // apparently this is needed to preemptively send the auth, for servers that dont require it but // dont send the same data if you're authenticated or not. try { m.addHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), m)); } catch (AuthenticationException a) { Log.warning(LOGGER_NAME, "Failed to add the authentication Header, error is: " + a.getMessage()); } ; final ClientHttpResponse httpResponse = factory.execute(m, new UsernamePasswordCredentials(username, password), AuthScope.ANY); try { status = httpResponse.getRawStatusCode(); if (Log.isDebugEnabled(LOGGER_NAME)) { Log.debug(LOGGER_NAME, "status:" + status); } if (saveResponse) { this.response = IOUtils.toString(httpResponse.getBody()); } } finally { httpResponse.close(); } return status; }
From source file:at.orz.arangodb.http.HttpManager.java
/** * /*from w w w. jav a2 s . co m*/ * @param requestEntity * @return * @throws ArangoException */ public HttpResponseEntity execute(HttpRequestEntity requestEntity) throws ArangoException { String url = buildUrl(requestEntity); if (logger.isDebugEnabled()) { if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT || requestEntity.type == RequestType.PATCH) { logger.debug("[REQ]http-{}: url={}, headers={}, body={}", new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText }); } else { logger.debug("[REQ]http-{}: url={}, headers={}", new Object[] { requestEntity.type, url, requestEntity.headers }); } } HttpRequestBase request = null; switch (requestEntity.type) { case GET: request = new HttpGet(url); break; case POST: HttpPost post = new HttpPost(url); configureBodyParams(requestEntity, post); request = post; break; case PUT: HttpPut put = new HttpPut(url); configureBodyParams(requestEntity, put); request = put; break; case PATCH: HttpPatch patch = new HttpPatch(url); configureBodyParams(requestEntity, patch); request = patch; break; case HEAD: request = new HttpHead(url); break; case DELETE: request = new HttpDelete(url); break; } // common-header String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.0; +http://mt.orz.at/)"; // TODO: request.setHeader("User-Agent", userAgent); //request.setHeader("Content-Type", "binary/octet-stream"); // optinal-headers if (requestEntity.headers != null) { for (Entry<String, Object> keyValue : requestEntity.headers.entrySet()) { request.setHeader(keyValue.getKey(), keyValue.getValue().toString()); } } // Basic Auth Credentials credentials = null; if (requestEntity.username != null && requestEntity.password != null) { credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password); } else if (configure.getUser() != null && configure.getPassword() != null) { credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword()); } if (credentials != null) { request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false)); } // CURL/httpie Logger if (configure.isEnableCURLLogger()) { CURLLogger.log(url, requestEntity, userAgent, credentials); } HttpResponse response = null; try { response = client.execute(request); if (response == null) { return null; } HttpResponseEntity responseEntity = new HttpResponseEntity(); // http status StatusLine status = response.getStatusLine(); responseEntity.statusCode = status.getStatusCode(); responseEntity.statusPhrase = status.getReasonPhrase(); logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode); // ?? //// TODO etag??? Header etagHeader = response.getLastHeader("etag"); if (etagHeader != null) { responseEntity.etag = Long.parseLong(etagHeader.getValue().replace("\"", "")); } // Map??? responseEntity.headers = new TreeMap<String, String>(); for (Header header : response.getAllHeaders()) { responseEntity.headers.put(header.getName(), header.getValue()); } // ??? HttpEntity entity = response.getEntity(); if (entity != null) { Header contentType = entity.getContentType(); if (contentType != null) { responseEntity.contentType = contentType.getValue(); if (responseEntity.isDumpResponse()) { responseEntity.stream = entity.getContent(); logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue()); } } // Close stream in this method. if (responseEntity.stream == null) { responseEntity.text = IOUtils.toString(entity.getContent()); logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text); } } return responseEntity; } catch (ClientProtocolException e) { throw new ArangoException(e); } catch (IOException e) { throw new ArangoException(e); } }
From source file:nl.esciencecenter.ptk.web.WebClient.java
/** * Execute Put or Post method and handle the (optional) String response. * Returns actual HTTP Status. Method does not do any (http) response status * handling. If the Put method succeeded but the HTTP status != 200 then * this value is returned and no Exception is thrown. * /*from w ww .j av a 2 s .com*/ * @param putOrPostmethod * - HttpPut or HttpPost method to execute * @param responseTextHolder * - Optional StringHolder for the Response: Put and Post might * nor return any response. * @param contentTypeHolder * - Optional StringHolder for the contentType (mimeType). * * @return actual HTTP Status as returned by server. * @throws WebException * if a communication error occurred. */ protected int executeAuthenticatedPut(HttpRequestBase putOrPostmethod, StringHolder responseTextHolder, StringHolder contentTypeHolder) throws WebException { if (this.httpClient == null) { throw new NullPointerException("HTTP Client not properly initialized: httpClient==null"); } logger.debugPrintf("executePutOrPost():'%s'\n", putOrPostmethod.getRequestLine()); boolean isPut = (putOrPostmethod instanceof HttpPut); boolean isPost = (putOrPostmethod instanceof HttpPost); if ((isPut == false) && (isPost == false)) { throw new IllegalArgumentException( "Method class must be either HttpPut or HttpPost. Class=" + putOrPostmethod.getClass()); } String actualUser; try { HttpResponse response; if (config.getUseBasicAuthentication()) { actualUser = config.getUsername(); String passwdStr = new String(config.getPasswordChars()); logger.debugPrintf("Using basic authentication, user=%s\n", actualUser); Header authHeader = new BasicHeader("Authorization", "Basic " + (StringUtil.base64Encode((actualUser + ":" + passwdStr).getBytes()))); putOrPostmethod.addHeader(authHeader); } response = httpClient.execute(putOrPostmethod); int status = handleStringResponse("executePutOrPost():" + putOrPostmethod.getRequestLine(), response, responseTextHolder, contentTypeHolder); this.lastHttpStatus = status; return status; } catch (ClientProtocolException e) { if ((config.getPort() == 443) && config.isHTTP()) { throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, "HTTP Protocol error: Trying to speak plain http to (SSL) port 443?\n" + e.getMessage(), e); } else if (config.isHTTPS()) { throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, "HTTPS Protocol error:" + e.getMessage(), e); } else { throw new WebException(WebException.Reason.HTTP_CLIENTEXCEPTION, "HTTP Protocol error:" + e.getMessage(), e); } } catch (javax.net.ssl.SSLPeerUnverifiedException e) { throw new WebException(WebException.Reason.HTTPS_SSLEXCEPTION, "SSL Error:Remote host not authenticated or couldn't verify host certificate.\n" + e.getMessage(), e); } catch (javax.net.ssl.SSLException e) { // Super class throw new WebException(WebException.Reason.HTTPS_SSLEXCEPTION, "SSL Error:Remote host not authenticated or couldn't verify host certificate.\n" + e.getMessage(), e); } catch (java.net.NoRouteToHostException e) { throw new WebException(WebException.Reason.NO_ROUTE_TO_HOST_EXCEPTION, "No route to host: Server could be down or unreachable.\n" + e.getMessage(), e); } catch (IOException e) { throw new WebException(WebException.Reason.IOEXCEPTION, e.getMessage(), e); } }
From source file:com.arangodb.http.HttpManager.java
/** * Executes the request/*ww w . j a v a 2s . co m*/ * * @param requestEntity * the request * @return the response of the request * @throws ArangoException */ private HttpResponseEntity executeInternal(String baseUrl, HttpRequestEntity requestEntity) throws ArangoException, SocketException { String url = buildUrl(baseUrl, requestEntity); if (logger.isDebugEnabled()) { if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT || requestEntity.type == RequestType.PATCH) { logger.debug("[REQ]http-{}: url={}, headers={}, body={}", new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText }); } else { logger.debug("[REQ]http-{}: url={}, headers={}", new Object[] { requestEntity.type, url, requestEntity.headers }); } } HttpRequestBase request = null; switch (requestEntity.type) { case GET: request = new HttpGet(url); break; case POST: HttpPost post = new HttpPost(url); configureBodyParams(requestEntity, post); request = post; break; case PUT: HttpPut put = new HttpPut(url); configureBodyParams(requestEntity, put); request = put; break; case PATCH: HttpPatch patch = new HttpPatch(url); configureBodyParams(requestEntity, patch); request = patch; break; case HEAD: request = new HttpHead(url); break; case DELETE: request = new HttpDelete(url); break; } // common-header String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.1; +http://mt.orz.at/)"; request.setHeader("User-Agent", userAgent); // optinal-headers if (requestEntity.headers != null) { for (Entry<String, Object> keyValue : requestEntity.headers.entrySet()) { request.setHeader(keyValue.getKey(), keyValue.getValue().toString()); } } // Basic Auth Credentials credentials = null; if (requestEntity.username != null && requestEntity.password != null) { credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password); } else if (configure.getUser() != null && configure.getPassword() != null) { credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword()); } if (credentials != null) { BasicScheme basicScheme = new BasicScheme(); try { request.addHeader(basicScheme.authenticate(credentials, request, null)); } catch (AuthenticationException e) { throw new ArangoException(e); } } if (this.getHttpMode().equals(HttpMode.ASYNC)) { request.addHeader("x-arango-async", "store"); } else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) { request.addHeader("x-arango-async", "true"); } // CURL/httpie Logger if (configure.isEnableCURLLogger()) { CURLLogger.log(url, requestEntity, userAgent, credentials); } HttpResponse response = null; if (preDefinedResponse != null) { return preDefinedResponse; } try { response = client.execute(request); if (response == null) { return null; } HttpResponseEntity responseEntity = new HttpResponseEntity(); // http status StatusLine status = response.getStatusLine(); responseEntity.statusCode = status.getStatusCode(); responseEntity.statusPhrase = status.getReasonPhrase(); logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode); // ?? // // TODO etag??? Header etagHeader = response.getLastHeader("etag"); if (etagHeader != null) { responseEntity.etag = Long.parseLong(etagHeader.getValue().replace("\"", "")); } // Map??? responseEntity.headers = new TreeMap<String, String>(); for (Header header : response.getAllHeaders()) { responseEntity.headers.put(header.getName(), header.getValue()); } // ??? HttpEntity entity = response.getEntity(); if (entity != null) { Header contentType = entity.getContentType(); if (contentType != null) { responseEntity.contentType = contentType.getValue(); if (responseEntity.isDumpResponse()) { responseEntity.stream = entity.getContent(); logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue()); } } // Close stream in this method. if (responseEntity.stream == null) { responseEntity.text = IOUtils.toString(entity.getContent()); logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text); } } if (this.getHttpMode().equals(HttpMode.ASYNC)) { Map<String, String> map = responseEntity.getHeaders(); this.addJob(map.get("X-Arango-Async-Id"), this.getCurrentObject()); } else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) { return null; } return responseEntity; } catch (SocketException ex) { throw ex; } catch (ClientProtocolException e) { throw new ArangoException(e); } catch (IOException e) { throw new ArangoException(e); } }
From source file:org.georchestra.security.HeadersManagementStrategy.java
private void handleRequestCookies(HttpServletRequest originalRequest, HttpRequestBase proxyRequest, StringBuilder headersLog) { Enumeration<String> headers = originalRequest.getHeaders(COOKIE_ID); StringBuilder cookies = new StringBuilder(); while (headers.hasMoreElements()) { String value = headers.nextElement(); for (String requestCookies : value.split(";")) { String trimmed = requestCookies.trim(); if (trimmed.length() > 0) { if (!trimmed.startsWith(HeaderNames.JSESSION_ID)) { if (cookies.length() > 0) cookies.append("; "); cookies.append(trimmed); }/*from w w w .java 2 s . co m*/ } } } HttpSession session = originalRequest.getSession(); String requestPath = proxyRequest.getURI().getPath(); if (session != null && session.getAttribute(HeaderNames.JSESSION_ID) != null) { Map<String, String> jessionIds = (Map) session.getAttribute(HeaderNames.JSESSION_ID); String currentPath = null; String currentId = null; for (String path : jessionIds.keySet()) { // see https://www.owasp.org/index.php/HttpOnly // removing extra suffixes for JSESSIONID cookie ("; HttpOnly") // This is related to some issues with newer versions of tomcat // and session loss, e.g.: // https://github.com/georchestra/georchestra/pull/913 String actualPath = path.split(";")[0].trim(); // the cookie we will use is the cookie with the longest matching path if (requestPath.startsWith(actualPath)) { if (logger.isDebugEnabled()) { logger.debug("Found possible matching JSessionId: Path = " + actualPath + " id=" + jessionIds.get(path) + " for " + requestPath + " of uri " + proxyRequest.getURI()); } if (currentPath == null || currentPath.length() < actualPath.length()) { currentPath = actualPath; currentId = jessionIds.get(path); } } } if (currentPath != null) { if (cookies.length() > 0) cookies.append("; "); cookies.append(currentId); } } headersLog.append("\t" + COOKIE_ID); headersLog.append("="); headersLog.append(cookies); headersLog.append("\n"); proxyRequest.addHeader(new BasicHeader(COOKIE_ID, cookies.toString())); }
From source file:org.georchestra.security.HeadersManagementStrategy.java
/** * Copies the request headers from the original request to the proxy request. It may modify the * headers slightly//from w ww . j av a2 s. c o m */ @SuppressWarnings("unchecked") public synchronized void configureRequestHeaders(HttpServletRequest originalRequest, HttpRequestBase proxyRequest) { Enumeration<String> headerNames = originalRequest.getHeaderNames(); String headerName = null; StringBuilder headersLog = new StringBuilder("Request Headers:\n"); headersLog.append("==========================================================\n"); if (referer != null) { addHeaderToRequestAndLog(proxyRequest, headersLog, REFERER_HEADER_NAME, this.referer); } while (headerNames.hasMoreElements()) { headerName = headerNames.nextElement(); if (headerName.compareToIgnoreCase(CONTENT_LENGTH) == 0) { continue; } if (headerName.equalsIgnoreCase(COOKIE_ID)) { continue; } if (filter(originalRequest, headerName, proxyRequest)) { continue; } if (noAcceptEncoding && headerName.equalsIgnoreCase(ACCEPT_ENCODING)) { continue; } if (headerName.equalsIgnoreCase(HOST)) { continue; } // Don't forward 'sec-*' headers, those headers must be managed by security-proxy if (headerName.toLowerCase().startsWith(PROTECTED_HEADER_PREFIX)) { continue; } if (referer != null && headerName.equalsIgnoreCase(REFERER_HEADER_NAME)) { continue; } String value = originalRequest.getHeader(headerName); addHeaderToRequestAndLog(proxyRequest, headersLog, headerName, value); } // see https://github.com/georchestra/georchestra/issues/509: addHeaderToRequestAndLog(proxyRequest, headersLog, SEC_PROXY, "true"); handleRequestCookies(originalRequest, proxyRequest, headersLog); HttpSession session = originalRequest.getSession(); for (HeaderProvider provider : headerProviders) { for (Header header : provider.getCustomRequestHeaders(session, originalRequest)) { if ((header.getName().equalsIgnoreCase(SEC_USERNAME) || header.getName().equalsIgnoreCase(SEC_ROLES)) && proxyRequest.getHeaders(header.getName()) != null && proxyRequest.getHeaders(header.getName()).length > 0) { Header[] originalHeaders = proxyRequest.getHeaders(header.getName()); for (Header originalHeader : originalHeaders) { headersLog.append("\t" + originalHeader.getName()); headersLog.append("="); headersLog.append(originalHeader.getValue()); headersLog.append("\n"); } } else { proxyRequest.addHeader(header); headersLog.append("\t" + header.getName()); headersLog.append("="); headersLog.append(header.getValue()); headersLog.append("\n"); } } } headersLog.append("=========================================================="); logger.trace(headersLog.toString()); }