List of usage examples for org.apache.commons.httpclient HttpMethodBase addRequestHeader
@Override public void addRequestHeader(String headerName, String headerValue)
From source file:org.opentides.util.UrlUtil.java
/** * Returns the HTML code of the original engine. Takes the URL to connect to * the engine. Also takes encoding type that overrides default if not null * "UTF8" is typical encoding type//w w w. ja v a2 s .c o m * * @param queryURL * - URL of engine to retrieve * @param request * - request object * @param param * - additional parameters * - Valid parameters are: * - methodName - Either "POST" or "GET". Default is "POST" * - forwardCookie - if true, will forward cookies found on request object * - IPAddress - if specified, this IP will be used for the request * */ public static final UrlResponseObject getPage(final String queryURL, final HttpServletRequest request, final Map<String, Object> param) { // determine if get or post method HttpMethodBase httpMethodBase; Boolean forwardCookie = false; InetAddress IPAddress = null; if (param != null) { if (param.get("forwardCookie") != null) forwardCookie = (Boolean) param.get("forwardCookie"); if (param.get("IPAddress") != null) { String IPString = (String) param.get("IPAddress"); if (!StringUtil.isEmpty(IPString)) { IPAddress = convertIPString(IPString); } } } if (param != null && "GET".equals((String) param.get("methodName"))) { httpMethodBase = new GetMethod(queryURL); } else { httpMethodBase = new PostMethod(queryURL); } try { // declare the connection objects HttpClient client = new HttpClient(); HostConfiguration hostConfig = new HostConfiguration(); String userAgent = request.getHeader("User-Agent"); // for debugging if (_log.isDebugEnabled()) _log.debug("Retrieving page from " + queryURL); // initialize the connection settings client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT); client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); httpMethodBase.addRequestHeader("accept", "*/*"); httpMethodBase.addRequestHeader("accept-language", "en-us"); httpMethodBase.addRequestHeader("user-agent", userAgent); if (forwardCookie) { // get cookies from request Cookie[] cookies = request.getCookies(); String cookieString = ""; for (Cookie c : cookies) { cookieString += c.getName() + "=" + c.getValue() + "; "; } // forward cookies to httpMethod httpMethodBase.setRequestHeader("Cookie", cookieString); } if (IPAddress != null) { hostConfig.setLocalAddress(IPAddress); } // Setup for 3 retry httpMethodBase.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // now let's retrieve the data client.executeMethod(hostConfig, httpMethodBase); // Read the response body. UrlResponseObject response = new UrlResponseObject(); response.setResponseBody(httpMethodBase.getResponseBody()); Header contentType = httpMethodBase.getResponseHeader("Content-Type"); if (contentType != null) response.setResponseType(contentType.getValue()); else response.setResponseType(Widget.TYPE_HTML); return response; } catch (Exception ex) { _log.error("Failed to request from URL: [" + queryURL + "]", ex); return null; } finally { try { httpMethodBase.releaseConnection(); } catch (Exception ignored) { } } }
From source file:org.opentides.util.WidgetUtil.java
/** * Returns the HTML code of the original engine. Takes the URL to connect to * the engine. Also takes encoding type that overrides default if not null * "UTF8" is typical encoding type/* w w w . ja v a2 s . co m*/ * * @param queryURL * - URL of engine to retrieve * @param request * - request object * @param param * - additional parameters * - Valid parameters are: * - methodName - Either "POST" or "GET". Default is "POST" * - forwardCookie - if true, will forward cookies found on request object * - IPAddress - if specified, this IP will be used for the request * */ public static final UrlResponseObject getPage(final String queryURL, final HttpServletRequest request, final Map<String, Object> param) { // determine if get or post method HttpMethodBase httpMethodBase; Boolean forwardCookie = false; InetAddress IPAddress = null; if (param != null) { if (param.get("forwardCookie") != null) forwardCookie = (Boolean) param.get("forwardCookie"); if (param.get("IPAddress") != null) { String IPString = (String) param.get("IPAddress"); if (!StringUtil.isEmpty(IPString)) { IPAddress = UrlUtil.convertIPString(IPString); } } } if (param != null && "GET".equals((String) param.get("methodName"))) { httpMethodBase = new GetMethod(queryURL); } else { httpMethodBase = new PostMethod(queryURL); } try { // declare the connection objects HttpClient client = new HttpClient(); HostConfiguration hostConfig = new HostConfiguration(); String userAgent = request.getHeader("User-Agent"); // for debugging if (_log.isDebugEnabled()) _log.debug("Retrieving page from " + queryURL); // initialize the connection settings client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT); client.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); httpMethodBase.addRequestHeader("accept", "*/*"); httpMethodBase.addRequestHeader("accept-language", "en-us"); httpMethodBase.addRequestHeader("user-agent", userAgent); if (forwardCookie) { // get cookies from request Cookie[] cookies = request.getCookies(); String cookieString = ""; for (Cookie c : cookies) { cookieString += c.getName() + "=" + c.getValue() + "; "; } // forward cookies to httpMethod httpMethodBase.setRequestHeader("Cookie", cookieString); } if (IPAddress != null) { hostConfig.setLocalAddress(IPAddress); } // Setup for 3 retry httpMethodBase.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // now let's retrieve the data client.executeMethod(hostConfig, httpMethodBase); // Read the response body. UrlResponseObject response = new UrlResponseObject(); response.setResponseBody(httpMethodBase.getResponseBody()); Header contentType = httpMethodBase.getResponseHeader("Content-Type"); if (contentType != null) response.setResponseType(contentType.getValue()); else response.setResponseType("html"); return response; } catch (Exception ex) { _log.error("Failed to request from URL: [" + queryURL + "]", ex); return null; } finally { try { httpMethodBase.releaseConnection(); } catch (Exception ignored) { } } }
From source file:org.paxml.bean.HttpTag.java
private HttpMethodBase setHeader(HttpMethodBase method) { Map<String, List<String>> value = getNameValuePairs(header, "header"); if (value != null) { for (Map.Entry<String, List<String>> entry : value.entrySet()) { for (String v : entry.getValue()) { method.addRequestHeader(entry.getKey(), v); }//from w w w. j a v a2 s. com } } else if (header != null) { throw new PaxmlRuntimeException("Header should be key-value pairs but got: " + header); } return method; }
From source file:org.review_board.ereviewboard.core.client.ReviewboardHttpClient.java
private void configureRequestForJson(HttpMethodBase request) { request.addRequestHeader("Accept", "application/json"); if (request instanceof PutMethod) request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); }
From source file:org.sonatype.nexus.restlight.common.AbstractRESTLightClient.java
@SuppressWarnings("unchecked") private void addRequestParams(final HttpMethodBase method, final Map<String, ? extends Object> requestParams) { if (requestParams == null) { return;//from ww w .j a v a 2s . co m } for (Map.Entry<String, ? extends Object> entry : requestParams.entrySet()) { if (entry.getValue() instanceof Collection) { Collection<Object> values = (Collection<Object>) entry.getValue(); if (values != null && !values.isEmpty()) { for (Object val : values) { if (val != null) { method.addRequestHeader(entry.getKey(), String.valueOf(val)); } } } } else { method.addRequestHeader(entry.getKey(), String.valueOf(entry.getValue())); } } }
From source file:org.springfield.mojo.http.HttpHelper.java
/** * Sends a standard HTTP request to the specified URI using the determined method. * Attaches the content, uses the specified content type, sets cookies, timeout and * request headers/*from w w w. ja v a 2 s . c o m*/ * * @param method - the request method * @param uri - the uri to request * @param body - the content * @param contentType - the content type * @param cookies - cookies * @param timeout - timeout in milliseconds * @param charSet - the character set * @param requestHeaders - extra user defined headers * @return response */ public static Response sendRequest(String method, String uri, String body, String contentType, String cookies, int timeout, String charSet, Map<String, String> requestHeaders) { // http client HttpClient client = new HttpClient(); // method HttpMethodBase reqMethod = null; if (method.equals(HttpMethods.PUT)) { reqMethod = new PutMethod(uri); } else if (method.equals(HttpMethods.POST)) { reqMethod = new PostMethod(uri); } else if (method.equals(HttpMethods.GET)) { if (body != null) { // hack to be able to send a request body with a get (only if required) reqMethod = new PostMethod(uri) { public String getName() { return "GET"; } }; } else { reqMethod = new GetMethod(uri); } } else if (method.equals(HttpMethods.DELETE)) { if (body != null) { // hack to be able to send a request body with a delete (only if required) reqMethod = new PostMethod(uri) { public String getName() { return "DELETE"; } }; } else { reqMethod = new DeleteMethod(uri); } } else if (method.equals(HttpMethods.HEAD)) { reqMethod = new HeadMethod(uri); } else if (method.equals(HttpMethods.TRACE)) { reqMethod = new TraceMethod(uri); } else if (method.equals(HttpMethods.OPTIONS)) { reqMethod = new OptionsMethod(uri); } // add request body if (body != null) { try { RequestEntity entity = new StringRequestEntity(body, contentType, charSet); ((EntityEnclosingMethod) reqMethod).setRequestEntity(entity); reqMethod.setRequestHeader("Content-type", contentType); } catch (Exception e) { e.printStackTrace(); } } // add cookies if (cookies != null) { reqMethod.addRequestHeader("Cookie", cookies); } // add custom headers if (requestHeaders != null) { for (Map.Entry<String, String> header : requestHeaders.entrySet()) { String name = header.getKey(); String value = header.getValue(); reqMethod.addRequestHeader(name, value); } } Response response = new Response(); // do request try { if (timeout != -1) { client.getParams().setSoTimeout(timeout); } int statusCode = client.executeMethod(reqMethod); response.setStatusCode(statusCode); } catch (Exception e) { e.printStackTrace(); } // read response try { InputStream instream = reqMethod.getResponseBodyAsStream(); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int len; while ((len = instream.read(buffer)) > 0) { outstream.write(buffer, 0, len); } String resp = new String(outstream.toByteArray(), reqMethod.getResponseCharSet()); response.setResponse(resp); //set content length long contentLength = reqMethod.getResponseContentLength(); response.setContentLength(contentLength); //set character set String respCharSet = reqMethod.getResponseCharSet(); response.setCharSet(respCharSet); //set all headers Header[] headers = reqMethod.getResponseHeaders(); response.setHeaders(headers); } catch (Exception e) { e.printStackTrace(); } // release connection reqMethod.releaseConnection(); // return return response; }
From source file:org.tinygroup.httpvisit.impl.HttpVisitorImpl.java
String execute(HttpMethodBase method) { try {//from www . j a v a 2 s. com if (client == null) { init(); } LOGGER.logMessage(LogLevel.DEBUG, "?:{}", method.getURI().toString()); if (!("ISO-8859-1").equals(requestCharset)) { method.addRequestHeader("Content-Type", "text/html; charset=" + requestCharset); } method.setDoAuthentication(authEnabled); int iGetResultCode = client.executeMethod(method); if (iGetResultCode == HttpStatus.SC_OK) { LOGGER.logMessage(LogLevel.DEBUG, "?"); Header responseHeader = method.getResponseHeader("Content-Encoding"); if (responseHeader != null) { String acceptEncoding = responseHeader.getValue(); if (acceptEncoding != null && ("gzip").equals(acceptEncoding)) { //gzip? ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( method.getResponseBody()); GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream); return IOUtils.readFromInputStream(gzipInputStream, responseCharset); } } return new String(method.getResponseBody(), responseCharset); } LOGGER.logMessage(LogLevel.ERROR, "{}", method.getStatusLine().toString()); throw new RuntimeException(method.getStatusLine().toString()); } catch (Exception e) { LOGGER.logMessage(LogLevel.DEBUG, "{}", e.getMessage()); throw new RuntimeException(e); } finally { method.releaseConnection(); } }
From source file:org.wings.recorder.Script.java
private void addHeaders(Request request, HttpMethodBase post) { List headers = request.getHeaders(); for (Iterator iterator = headers.iterator(); iterator.hasNext();) { Request.Header header = (Request.Header) iterator.next(); post.addRequestHeader(header.getName(), header.getValue()); }//w w w . j av a 2 s .c om }
From source file:org.wso2.carbon.identity.cloud.listener.claim.onprem.CloudClaimManagerListener.java
protected void setAuthorizationHeader(HttpMethodBase request) throws ClaimManagerListenerException { String token;/*from w w w.j ava 2s . c o m*/ SecurityTokenBuilder securityTokenBuilder = new DefaultJWTGenerator(); token = securityTokenBuilder.buildSecurityToken(getTenantPrivateKey(tenantId)); request.addRequestHeader("Authorization", "Bearer " + token); }
From source file:org.wso2.carbon.identity.user.store.ws.WSUserStoreManager.java
protected void setAuthorizationHeader(HttpMethodBase request) throws WSUserStoreException { String token;// w w w. jav a 2 s . c om SecurityTokenBuilder securityTokenBuilder = new DefaultJWTGenerator(); token = securityTokenBuilder.buildSecurityToken(getTenantPrivateKey(tenantId)); request.addRequestHeader("Authorization", "Bearer " + token); }