List of usage examples for org.apache.commons.httpclient HttpMethod addRequestHeader
public abstract void addRequestHeader(Header paramHeader);
From source file:org.eclipse.orion.server.cf.utils.HttpUtil.java
public static void configureHttpMethod(HttpMethod method, Target target) throws JSONException { method.addRequestHeader(new Header("Accept", "application/json")); method.addRequestHeader(new Header("Content-Type", "application/json")); //set default socket timeout for connection HttpMethodParams params = method.getParams(); params.setSoTimeout(DEFAULT_SOCKET_TIMEOUT); method.setParams(params);/*from w ww .j av a 2 s. c o m*/ if (target.getCloud().getAccessToken() != null) method.addRequestHeader(new Header("Authorization", "bearer " + target.getCloud().getAccessToken().getString("access_token"))); }
From source file:org.eclipse.orion.server.cf.utils.HttpUtil.java
public static void configureHttpMethod(HttpMethod method, Cloud cloud) throws JSONException { method.addRequestHeader(new Header("Accept", "application/json")); method.addRequestHeader(new Header("Content-Type", "application/json")); //set default socket timeout for connection HttpMethodParams params = method.getParams(); params.setSoTimeout(DEFAULT_SOCKET_TIMEOUT); method.setParams(params);//from w ww .ja va 2 s . c o m if (cloud.getAccessToken() != null) method.addRequestHeader( new Header("Authorization", "bearer " + cloud.getAccessToken().getString("access_token"))); }
From source file:org.eclipse.smarthome.io.net.http.HttpUtil.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * /*from w w w . j ava 2 s . c om*/ * @param httpMethod the HTTP method to use * @param url the url to execute (in milliseconds) * @param httpHeaders optional HTTP headers which has to be set on request * @param content the content to be send to the given <code>url</code> or * <code>null</code> if no content should be send. * @param contentType the content type of the given <code>content</code> * @param timeout the socket timeout to wait for data * @param proxyHost the hostname of the proxy * @param proxyPort the port of the proxy * @param proxyUser the username to authenticate with the proxy * @param proxyPassword the password to authenticate with the proxy * @param nonProxyHosts the hosts that won't be routed through the proxy * @return the response body or <code>NULL</code> when the request went wrong */ public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) { HttpClient client = new HttpClient(); // only configure a proxy if a host is provided if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotBlank(proxyUser)) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); } } HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (httpHeaders != null) { for (String httpHeaderKey : httpHeaders.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey))); } } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } Credentials credentials = extractCredentials(url); if (credentials != null) { client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.debug(e.getMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.debug(responseBody); } return responseBody; } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return null; }
From source file:org.exist.xquery.modules.httpclient.BaseHTTPClientFunction.java
/** * Parses header parameters and sets them on the Request. * * @param method The Http Method to set the request headers on * @param headers The headers node e.g. <headers><header name="Content-Type" value="application/xml"/></headers> * * @throws XPathException //from w ww .j a va 2 s. com */ protected void setHeaders(final HttpMethod method, final Node headers) throws XPathException { if ((headers.getNodeType() == Node.ELEMENT_NODE) && headers.getLocalName().equals("headers")) { final NodeList headerList = headers.getChildNodes(); for (int i = 0; i < headerList.getLength(); i++) { final Node header = headerList.item(i); if ((header.getNodeType() == Node.ELEMENT_NODE) && header.getLocalName().equals("header")) { final String name = ((Element) header).getAttribute("name"); final String value = ((Element) header).getAttribute("value"); if (name == null || value == null) { throw new XPathException(this, "Name or value attribute missing for request header parameter"); } method.addRequestHeader(new Header(name, value)); } } } }
From source file:org.infoscoop.request.filter.ProxyFilterContainer.java
public final int invoke(HttpClient client, HttpMethod method, ProxyRequest request) throws Exception { int preStatus = prepareInvoke(client, method, request); switch (preStatus) { case 0:/*ww w.ja va 2s . c om*/ break; case EXECUTE_POST_STATUS: doFilterChain(request, request.getResponseBody()); default: return preStatus; } // copy headers sent target server List ignoreHeaderNames = request.getIgnoreHeaders(); List allowedHeaderNames = request.getAllowedHeaders(); boolean allowAllHeader = false; Proxy proxy = request.getProxy(); if (proxy != null) { allowAllHeader = proxy.isAllowAllHeader(); if (!allowAllHeader) allowedHeaderNames.addAll(proxy.getAllowedHeaders()); } AuthenticatorUtil.doAuthentication(client, method, request); StringBuffer headersSb = new StringBuffer(); for (String name : request.getRequestHeaders().keySet()) { String value = request.getRequestHeader(name); String lowname = name.toLowerCase(); if (!allowAllHeader && !allowedHeaderNames.contains(lowname)) continue; if (ignoreHeaderNames.contains(lowname)) continue; if ("cookie".equalsIgnoreCase(name)) { if (proxy.getSendingCookies() != null) { value = RequestUtil.removeCookieParam(value, proxy.getSendingCookies()); } } if ("if-modified-since".equalsIgnoreCase(name) && "Thu, 01 Jun 1970 00:00:00 GMT".equals(value)) continue; method.addRequestHeader(new Header(name, value)); headersSb.append(name + "=" + value + ", "); } int cacheStatus = getCache(client, method, request); if (cacheStatus != 0) return cacheStatus; if (log.isInfoEnabled()) log.info("RequestHeader: " + headersSb); // execute http method and process redirect method.setFollowRedirects(false); client.executeMethod(method); int statusCode = method.getStatusCode(); for (int i = 0; statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_SEE_OTHER || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT; i++) { // connection release method.releaseConnection(); if (i == 5) { log.error("The circular redirect is limited by five times."); return 500; } Header location = method.getResponseHeader("Location"); String redirectUrl = location.getValue(); // According to 2,068 1.1 rfc http spec, we cannot appoint the relative URL, // but microsoft.com gives back the relative URL. if (redirectUrl.startsWith("/")) { URI baseURI = method.getURI(); baseURI.setPath(redirectUrl); redirectUrl = baseURI.toString(); } //method.setURI(new URI(redirectUrl, false)); Header[] headers = method.getRequestHeaders(); method = new GetMethod(redirectUrl); for (int j = 0; j < headers.length; j++) { String headerName = headers[j].getName(); if (!headerName.equalsIgnoreCase("content-length") && !headerName.equalsIgnoreCase("authorization")) method.setRequestHeader(headers[j]); } AuthenticatorUtil.doAuthentication(client, method, request); method.setRequestHeader("authorization", request.getRequestHeader("Authorization")); method.setFollowRedirects(false); client.executeMethod(method); statusCode = method.getStatusCode(); request.setRedirectURL(redirectUrl); if (log.isInfoEnabled()) log.info("Redirect " + request.getTargetURL() + " to " + location + "."); } // copy response headers to proxyReqeust Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { request.putResponseHeader(headers[i].getName(), headers[i].getValue()); } if (log.isInfoEnabled()) log.info("Original Status:" + statusCode); // check response code if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { log.error("Proxy Authentication Required. Confirm ajax proxy setting."); throw new Exception( "Http Status 407, Proxy Authentication Required. Please contuct System Administrator."); } if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_RESET_CONTENT) { return statusCode; } else if (statusCode < 200 || statusCode >= 300) { request.setResponseBody(method.getResponseBodyAsStream()); return statusCode; } // process response body InputStream responseStream = null; if (statusCode != HttpStatus.SC_NO_CONTENT) { if (request.allowUserPublicCache()) { byte[] responseBody = method.getResponseBody(); Map<String, List<String>> responseHeaders = request.getResponseHeaders(); if (request.getRedirectURL() != null) responseHeaders.put("X-IS-REDIRECTED-FROM", Arrays.asList(new String[] { request.getRedirectURL() })); if (method instanceof GetMethod) { putCache(request.getOriginalURL(), new ByteArrayInputStream(responseBody), responseHeaders); } responseStream = new ByteArrayInputStream(responseBody); } else { responseStream = method.getResponseBodyAsStream(); } } doFilterChain(request, responseStream); return statusCode != HttpStatus.SC_NO_CONTENT ? method.getStatusCode() : 200; }
From source file:org.intalio.tempo.workflow.tas.core.WDSStorageStrategy.java
/** * Populates an {@link HttpMethod} with necessary headers to create a valid WDS request. *//*from www . j a va 2s . c o m*/ private void setUpMethod(HttpMethod method) { method.addRequestHeader(new Header("Participant-Token", "")); // TODO: use a token here }
From source file:org.mozilla.zest.impl.ZestBasicRunner.java
private void setHeaders(HttpMethod method, String headers) { if (headers == null) { return;//from w ww. ja va2 s . c o m } String[] headerArray = headers.split("\r\n"); String header; String value; for (String line : headerArray) { int colonIndex = line.indexOf(":"); if (colonIndex > 0) { header = line.substring(0, colonIndex); value = line.substring(colonIndex + 1).trim(); String lcHeader = header.toLowerCase(Locale.ROOT); if (!lcHeader.startsWith("cookie") && !lcHeader.startsWith("content-length")) { method.addRequestHeader(new Header(header, value)); } } } }
From source file:org.openhab.binding.garadget.internal.Connection.java
/** * Send a command to the Particle REST API (convenience function). * * @param device/*from w w w.ja v a 2 s . c o m*/ * the device context, or <code>null</code> if not needed for this command. * @param funcName * the function name to call, or variable/field to retrieve if <code>command</code> is * <code>null</code>. * @param user * the user name to use in Basic Authentication if the funcName would require Basic Authentication. * @param pass * the password to use in Basic Authentication if the funcName would require Basic Authentication. * @param command * the command to send to the API. * @param proc * a callback object that receives the status code and response body, or <code>null</code> if not * needed. */ public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command, HttpResponseHandler proc) { String url = null; String httpMethod = null; String content = null; String contentType = null; Properties headers = new Properties(); logger.trace("sendCommand: funcName={}", funcName); switch (funcName) { case "createToken": httpMethod = HTTP_POST; url = TOKEN_URL; content = command; contentType = APPLICATION_FORM_URLENCODED; break; case "deleteToken": httpMethod = HTTP_DELETE; url = String.format(ACCESS_TOKENS_URL, tokens.accessToken); break; case "getDevices": httpMethod = HTTP_GET; url = String.format(GET_DEVICES_URL, tokens.accessToken); break; default: url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken); if (command == null) { // retrieve a variable httpMethod = HTTP_GET; } else { // call a function httpMethod = HTTP_POST; content = command; contentType = APPLICATION_JSON; } break; } HttpClient client = new HttpClient(); // Only perform basic authentication when we aren't using OAuth if (!url.contains("access_token=")) { Credentials credentials = new UsernamePasswordCredentials(user, pass); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } HttpMethod method = createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); for (String httpHeaderKey : headers.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey))); logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey)); } try { // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null)); logger.trace("content='{}', contentType='{}'", content, contentType); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '{}'", method.getURI()); } catch (URIException e) { logger.debug(e.getMessage()); } } int statusCode = client.executeMethod(method); if (statusCode >= HttpStatus.SC_BAD_REQUEST) { logger.debug("Method failed: " + method.getStatusLine()); } String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.debug("Body of response: {}", responseBody); } if (proc != null) { proc.handleResponse(statusCode, responseBody); } } catch (HttpException he) { logger.warn("{}", he); } catch (IOException ioe) { logger.debug("{}", ioe); } finally { method.releaseConnection(); } }
From source file:org.openhab.binding.nest.internal.messages.AbstractRequest.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code>. In the case of httpMethods that do * not support automatic redirection, manually handle the HTTP temporary redirect (307) and retry with the new URL. * //from w w w. jav a 2 s . c o m * @param httpMethod * the HTTP method to use * @param url * the url to execute (in milliseconds) * @param contentString * the content to be sent to the given <code>url</code> or <code>null</code> if no content should be * sent. * @param contentType * the content type of the given <code>contentString</code> * @return the response body or <code>NULL</code> when the request went wrong */ protected final String executeUrl(final String httpMethod, final String url, final String contentString, final String contentType) { HttpClient client = new HttpClient(); HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(HTTP_REQUEST_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); for (String httpHeaderKey : HTTP_HEADERS.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, HTTP_HEADERS.getProperty(httpHeaderKey))); } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && contentString != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; InputStream content = new ByteArrayInputStream(contentString.getBytes()); eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } if (logger.isDebugEnabled()) { try { logger.trace("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.trace(e.getMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) { // perfectly fine but we cannot expect any answer... return null; } // Manually handle 307 redirects with a little tail recursion if (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) { Header[] headers = method.getResponseHeaders("Location"); String newUrl = headers[headers.length - 1].getValue(); return executeUrl(httpMethod, newUrl, contentString, contentType); } if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } InputStream tmpResponseStream = method.getResponseBodyAsStream(); Header encodingHeader = method.getResponseHeader("Content-Encoding"); if (encodingHeader != null) { for (HeaderElement ehElem : encodingHeader.getElements()) { if (ehElem.toString().matches(".*gzip.*")) { tmpResponseStream = new GZIPInputStream(tmpResponseStream); logger.trace("GZipped InputStream from {}", url); } else if (ehElem.toString().matches(".*deflate.*")) { tmpResponseStream = new InflaterInputStream(tmpResponseStream); logger.trace("Deflated InputStream from {}", url); } } } String responseBody = IOUtils.toString(tmpResponseStream); if (!responseBody.isEmpty()) { logger.trace(responseBody); } return responseBody; } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return null; }
From source file:org.openhab.io.net.http.HttpUtil.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * //ww w. j av a2 s . c o m * @param httpMethod the HTTP method to use * @param url the url to execute (in milliseconds) * @param httpHeaders optional HTTP headers which has to be set on request * @param content the content to be send to the given <code>url</code> or * <code>null</code> if no content should be send. * @param contentType the content type of the given <code>content</code> * @param timeout the socket timeout to wait for data * @param proxyHost the hostname of the proxy * @param proxyPort the port of the proxy * @param proxyUser the username to authenticate with the proxy * @param proxyPassword the password to authenticate with the proxy * @param nonProxyHosts the hosts that won't be routed through the proxy * @return the response body or <code>NULL</code> when the request went wrong */ public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) { HttpClient client = new HttpClient(); // only configure a proxy if a host is provided if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotBlank(proxyUser)) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); } } HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (httpHeaders != null) { for (String httpHeaderKey : httpHeaders.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey))); } } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } Credentials credentials = extractCredentials(url); if (credentials != null) { client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.debug(e.getMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) { // perfectly fine but we cannot expect any answer... return null; } if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } InputStream tmpResponseStream = method.getResponseBodyAsStream(); Header encodingHeader = method.getResponseHeader("Content-Encoding"); if (encodingHeader != null) { for (HeaderElement ehElem : encodingHeader.getElements()) { if (ehElem.toString().matches(".*gzip.*")) { tmpResponseStream = new GZIPInputStream(tmpResponseStream); logger.debug("GZipped InputStream from {}", url); } else if (ehElem.toString().matches(".*deflate.*")) { tmpResponseStream = new InflaterInputStream(tmpResponseStream); logger.debug("Deflated InputStream from {}", url); } } } String responseBody = IOUtils.toString(tmpResponseStream); if (!responseBody.isEmpty()) { logger.debug(responseBody); } return responseBody; } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return null; }