List of usage examples for org.apache.commons.httpclient HttpMethod addRequestHeader
public abstract void addRequestHeader(String paramString1, String paramString2);
From source file:org.sakaiproject.nakamura.proxy.ProxyClientServiceImpl.java
/** * @param method/*from w ww .ja v a 2s .co m*/ * @throws RepositoryException */ private void populateMethod(HttpMethod method, Node node, Map<String, String> headers) throws RepositoryException { // follow redirects, but dont auto process 401's and the like. // credentials should be provided method.setDoAuthentication(false); for (Entry<String, String> header : headers.entrySet()) { method.addRequestHeader(header.getKey(), header.getValue()); } Value[] additionalHeaders = JcrUtils.getValues(node, SAKAI_PROXY_HEADER); for (Value v : additionalHeaders) { String header = v.getString(); String[] keyVal = StringUtils.split(header, ':', 2); method.addRequestHeader(keyVal[0].trim(), keyVal[1].trim()); } }
From source file:org.soa4all.dashboard.gwt.module.wsmolite.server.WsmoLiteDataServiceImpl.java
@Override public String proxifyRequest(String method, String url, Map<String, String> headers) throws Exception { HttpMethod httpMtd; if (method.equalsIgnoreCase("post")) { httpMtd = new PostMethod(url); }/*from www . ja v a2s . c o m*/ if (method.equalsIgnoreCase("put")) { httpMtd = new PutMethod(url); } if (method.equalsIgnoreCase("delete")) { httpMtd = new DeleteMethod(url); } else { httpMtd = new GetMethod(url); } if (headers != null) { for (String key : headers.keySet()) { httpMtd.addRequestHeader(key, headers.get(key)); } } HttpClient httpclient = new HttpClient(); try { int result = httpclient.executeMethod(httpMtd); if (result != 200) { if (httpMtd.getResponseHeader("Error") != null) { throw new Exception(httpMtd.getResponseHeader("Error").getValue()); } throw new Exception("Service error code - " + result); } BufferedInputStream response = new BufferedInputStream(httpMtd.getResponseBodyAsStream()); ByteArrayOutputStream resultBuffer = new ByteArrayOutputStream(); byte[] buffer = new byte[1000]; int i; do { i = response.read(buffer); if (i > 0) { resultBuffer.write(buffer, 0, i); } } while (i > 0); httpMtd.releaseConnection(); return resultBuffer.toString("UTF-8"); } catch (Exception exc) { httpMtd.releaseConnection(); throw new Exception(exc.getClass().getSimpleName() + " : " + exc.getMessage()); } }
From source file:org.structr.web.Importer.java
private void copyURLToFile(final String uri, final java.io.File fileOnDisk) throws IOException { final HttpClient client = getHttpClient(); final HttpMethod get = new GetMethod(); get.setURI(new URI(uri, false)); get.addRequestHeader("User-Agent", "curl/7.35.0"); logger.log(Level.INFO, "Downloading from {0}", uri); final int statusCode = client.executeMethod(get); if (statusCode == 200) { try (final InputStream is = get.getResponseBodyAsStream()) { try (final OutputStream os = new FileOutputStream(fileOnDisk)) { IOUtils.copy(is, os);/* ww w. j ava2s .c o m*/ } } } else { System.out.println("response body: " + new String(get.getResponseBody(), "utf-8")); logger.log(Level.WARNING, "Unable to create file {0}: status code was {1}", new Object[] { uri, statusCode }); } }
From source file:org.tuckey.web.filters.urlrewrite.RequestProxy.java
private static HttpMethod setupProxyRequest(final HttpServletRequest hsRequest, final URL targetUrl) throws IOException { final String methodName = hsRequest.getMethod(); final HttpMethod method; if ("POST".equalsIgnoreCase(methodName)) { PostMethod postMethod = new PostMethod(); InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity( hsRequest.getInputStream()); postMethod.setRequestEntity(inputStreamRequestEntity); method = postMethod;//from ww w . j av a2 s . c om } else if ("GET".equalsIgnoreCase(methodName)) { method = new GetMethod(); } else if ("PUT".equalsIgnoreCase(methodName)) { PutMethod putMethod = new PutMethod(); InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity( hsRequest.getInputStream()); putMethod.setRequestEntity(inputStreamRequestEntity); method = putMethod; } else if ("DELETE".equalsIgnoreCase(methodName)) { method = new DeleteMethod(); } else { log.warn("Unsupported HTTP method requested: " + hsRequest.getMethod()); return null; } method.setFollowRedirects(false); method.setPath(targetUrl.getPath()); method.setQueryString(targetUrl.getQuery()); Enumeration e = hsRequest.getHeaderNames(); if (e != null) { while (e.hasMoreElements()) { String headerName = (String) e.nextElement(); if ("host".equalsIgnoreCase(headerName)) { //the host value is set by the http client continue; } else if ("content-length".equalsIgnoreCase(headerName)) { //the content-length is managed by the http client continue; } else if ("accept-encoding".equalsIgnoreCase(headerName)) { //the accepted encoding should only be those accepted by the http client. //The response stream should (afaik) be deflated. If our http client does not support //gzip then the response can not be unzipped and is delivered wrong. continue; } else if (headerName.toLowerCase().startsWith("cookie")) { //fixme : don't set any cookies in the proxied request, this needs a cleaner solution continue; } Enumeration values = hsRequest.getHeaders(headerName); while (values.hasMoreElements()) { String headerValue = (String) values.nextElement(); log.info("setting proxy request parameter:" + headerName + ", value: " + headerValue); method.addRequestHeader(headerName, headerValue); } } } if (log.isInfoEnabled()) log.info("proxy query string " + method.getQueryString()); return method; }
From source file:org.tuleap.mylyn.task.core.internal.client.rest.RestOperation.java
/** * Provides the Method to run.//from w ww. ja va 2 s . c om * * @return The method to run. */ public HttpMethod createMethod() { HttpMethod m = method.create(); if (m instanceof EntityEnclosingMethod) { StringRequestEntity entity; try { if (body == null) { entity = new StringRequestEntity(EMPTY_BODY, CONTENT_TYPE_JSON, ENCODING_UTF8); } else { entity = new StringRequestEntity(body, CONTENT_TYPE_JSON, ENCODING_UTF8); } } catch (UnsupportedEncodingException e) { logger.log(new Status(IStatus.ERROR, TuleapCoreActivator.PLUGIN_ID, TuleapCoreMessages.getString(TuleapCoreKeys.encodingUtf8NotSupported))); return null; } ((EntityEnclosingMethod) m).setRequestEntity(entity); } m.setPath(fullUrl); for (Entry<String, String> entry : requestHeaders.entrySet()) { m.addRequestHeader(entry.getKey(), entry.getValue()); } NameValuePair[] queryParams = new NameValuePair[requestParameters.size()]; int i = 0; for (Entry<String, String> entry : requestParameters.entries()) { queryParams[i++] = new NameValuePair(entry.getKey(), entry.getValue()); } m.setQueryString(queryParams); return m; }
From source file:org.wingsource.plugin.impl.gadget.bean.Gadget.java
private Response getResponse(String tokenId, String href, Map<String, String> requestParameters) { logger.finest("Fetching content using HttpClient....user-Id: " + tokenId); HttpClient hc = new HttpClient(); hc.getHttpConnectionManager().getParams().setConnectionTimeout(5000); HttpMethod method = new GetMethod(href); method.addRequestHeader("xx-wings-user-id", tokenId); ArrayList<NameValuePair> nvpList = new ArrayList<NameValuePair>(); Set<String> keys = requestParameters.keySet(); for (String key : keys) { String value = requestParameters.get(key); nvpList.add(new NameValuePair(key, value)); }//from w w w .j a v a2 s . com String qs = method.getQueryString(); if (qs != null) { String[] nvPairs = qs.split("&"); for (String nvPair : nvPairs) { String[] mapping = nvPair.split("="); nvpList.add(new NameValuePair(mapping[0], mapping[1])); } } method.setFollowRedirects(true); NameValuePair[] nvps = new NameValuePair[nvpList.size()]; nvps = nvpList.toArray(nvps); method.setQueryString(nvps); byte[] content = null; Header[] headers = null; try { hc.executeMethod(method); content = method.getResponseBody(); headers = method.getResponseHeaders(); } catch (HttpException e) { logger.log(Level.SEVERE, e.getMessage(), e); } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage(), e); } return new Response(content, headers); }
From source file:org.zaproxy.zap.extension.ascanrulesAlpha.CloudMetadataScanner.java
private static HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body, HttpMethodParams params) throws URIException { HttpMethod httpMethod = new ZapGetMethod(); httpMethod.setURI(header.getURI());/* www .jav a 2s . c om*/ httpMethod.setParams(params); params.setVersion(HttpVersion.HTTP_1_1); String msg = header.getHeadersAsString(); String[] split = Pattern.compile("\\r\\n", Pattern.MULTILINE).split(msg); String token = null; String name = null; String value = null; int pos = 0; for (int i = 0; i < split.length; i++) { token = split[i]; if (token.equals("")) { continue; } if ((pos = token.indexOf(":")) < 0) { return null; } name = token.substring(0, pos).trim(); value = token.substring(pos + 1).trim(); httpMethod.addRequestHeader(name, value); } if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) { EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod; post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes())); } httpMethod.setFollowRedirects(false); return httpMethod; }
From source file:smartrics.rest.client.RestClientImpl.java
private void addHeaders(HttpMethod m, RestRequest request) { for (RestData.Header h : request.getHeaders()) { m.addRequestHeader(h.getName(), h.getValue()); }/*from w w w. j a va 2s .c o m*/ }
From source file:smilehouse.opensyncro.defaultcomponents.http.HTTPUtils.java
/** * Makes a HTTP request to the specified url with a set of parameters, * request method, user name and password * // ww w . ja v a 2 s. c o m * @param url the <code>URL</code> to make a request to * @param method either "GET", "POST", "PUT" or "SOAP" * @param parameters two dimensional string array containing parameters to send in the request * @param user user name to submit in the request * @param password password to submit in the request * @param charsetName charset name used for message content encoding * @param responseCharsetName charset name used to decode HTTP responses, * or null to use default ("ISO-8859-1") * @param contentType Content-Type header value (without charset information) * for POST (and SOAP) type requests. If null, defaults to * "text/xml". * @return a string array containing the body of the response, the headers of * the response and possible error message * @throws Exception */ public static HTTPResponse makeRequest(URL url, String method, String[][] parameters, String user, String password, String charsetName, String responseCharsetName, String contentType) throws Exception { HttpClient httpclient = new HttpClient(); HttpMethod request_method = null; HTTPResponse responseData = new HTTPResponse(); NameValuePair[] names_values = null; String requestContentType; if (contentType != null && contentType.length() > 0) { requestContentType = contentType; } else { requestContentType = DEFAULT_CONTENT_TYPE; } if (parameters != null && method.equals("PUT") == false) { names_values = new NameValuePair[parameters.length]; for (int i = 0; i < parameters.length; i++) { names_values[i] = new NameValuePair(parameters[i][0], parameters[i][1]); } } if (method.equalsIgnoreCase("POST")) { request_method = new PostMethod(url.toString()); if (names_values != null) ((PostMethod) request_method).setRequestBody(names_values); } else if (method.equalsIgnoreCase("PUT")) { if (parameters == null) throw new Exception("No data to use in PUT request"); request_method = new PutMethod(url.toString()); StringRequestEntity sre = new StringRequestEntity(parameters[0][0]); ((PutMethod) request_method).setRequestEntity(sre); } else if (method.equalsIgnoreCase("SOAP")) { String urlString = url.toString() + "?"; String message = null; String action = null; for (int i = 0; i < parameters.length; i++) { if (parameters[i][0].equals(SOAPMESSAGE)) message = parameters[i][1]; else if (parameters[i][0].equals(SOAP_ACTION_HEADER)) action = parameters[i][1]; else urlString += parameters[i][0] + "=" + parameters[i][1] + "&"; } urlString = urlString.substring(0, urlString.length() - 1); request_method = new PostMethod(urlString); // Encoding content with requested charset StringRequestEntity sre = new StringRequestEntity(message, requestContentType, charsetName); ((PostMethod) request_method).setRequestEntity(sre); if (action != null) { request_method.setRequestHeader(SOAP_ACTION_HEADER, action); } // Adding charset also into header's Content-Type request_method.addRequestHeader(CONTENT_TYPE_HEADER, requestContentType + "; charset=" + charsetName); } else { request_method = new GetMethod(url.toString()); if (names_values != null) ((GetMethod) request_method).setQueryString(names_values); } user = (user == null || user.length() < 1) ? null : user; password = (password == null || password.length() < 1) ? null : password; if ((user != null & password == null) || (user == null & password != null)) { throw new Exception("Invalid username or password"); } if (user != null && password != null) { httpclient.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(user, password); httpclient.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds); request_method.setDoAuthentication(true); } try { httpclient.executeMethod(request_method); if (request_method.getStatusCode() != HttpStatus.SC_OK) { responseData .setResponseError(request_method.getStatusCode() + " " + request_method.getStatusText()); } //Write response header to the out string array Header[] headers = request_method.getResponseHeaders(); responseData.appendToHeaders("\nHTTP status " + request_method.getStatusCode() + "\n"); for (int i = 0; i < headers.length; i++) { responseData.appendToHeaders(headers[i].getName() + ": " + headers[i].getValue() + "\n"); } /* * TODO: By default, the response charset should be read from the Content-Type header of * the response and that should be used in the InputStreamReader constructor: * * <code>new InputStreamReader(request_method.getResponseBodyAsStream(), * ((HttpMethodBase)request_method).getResponseCharSet());</code> * * But for backwards compatibility, the charset used by default is now the one that the * HttpClient library chooses (ISO-8859-1). An alternative charset can be chosen, but in * no situation is the charset read from the response's Content-Type header. */ BufferedReader br = null; if (responseCharsetName != null) { br = new BufferedReader( new InputStreamReader(request_method.getResponseBodyAsStream(), responseCharsetName)); } else { br = new BufferedReader(new InputStreamReader(request_method.getResponseBodyAsStream())); } String responseline; //Write response body to the out string array while ((responseline = br.readLine()) != null) { responseData.appendToBody(responseline + "\n"); } } finally { request_method.releaseConnection(); } return responseData; }