List of usage examples for org.apache.commons.httpclient HttpMethod getResponseHeaders
public abstract Header[] getResponseHeaders();
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java
/** * Collect the HTTP header information and set them in the message context * //w w w . j a v a 2 s .co m * @param method * HttpMethodBase from which to get information * @param msgContext * the MessageContext in which to place the information... OR * NOT! * @throws AxisFault * if problems occur */ protected void obtainHTTPHeaderInformation(Object httpMethodBase, MessageContext msgContext) throws AxisFault { HttpMethod method; if (httpMethodBase instanceof HttpMethodBase) { method = (HttpMethod) httpMethodBase; } else { return; } // Set RESPONSE properties onto the REQUEST message context. They will // need to be copied off the request context onto // the response context elsewhere, for example in the // OutInOperationClient. Map transportHeaders = new HTTPTransportHeaders(method.getResponseHeaders()); msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, transportHeaders); msgContext.setProperty(HTTPConstants.MC_HTTP_STATUS_CODE, new Integer(method.getStatusCode())); Header header = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE); if (header != null) { HeaderElement[] headers = header.getElements(); MessageContext inMessageContext = msgContext.getOperationContext() .getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE); Object contentType = header.getValue(); Object charSetEnc = null; for (int i = 0; i < headers.length; i++) { NameValuePair charsetEnc = headers[i].getParameterByName(HTTPConstants.CHAR_SET_ENCODING); if (charsetEnc != null) { charSetEnc = charsetEnc.getValue(); } } if (inMessageContext != null) { inMessageContext.setProperty(Constants.Configuration.CONTENT_TYPE, contentType); inMessageContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); } else { // Transport details will be stored in a HashMap so that anybody // interested can // retrieve them HashMap transportInfoMap = new HashMap(); transportInfoMap.put(Constants.Configuration.CONTENT_TYPE, contentType); transportInfoMap.put(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc); // the HashMap is stored in the outgoing message. msgContext.setProperty(Constants.Configuration.TRANSPORT_INFO_MAP, transportInfoMap); } } String sessionCookie = null; // Process old style headers first Header[] cookieHeaders = method.getResponseHeaders(HTTPConstants.HEADER_SET_COOKIE); String customCoookiId = (String) msgContext.getProperty(Constants.CUSTOM_COOKIE_ID); for (int i = 0; i < cookieHeaders.length; i++) { HeaderElement[] elements = cookieHeaders[i].getElements(); for (int e = 0; e < elements.length; e++) { HeaderElement element = elements[e]; if (Constants.SESSION_COOKIE.equalsIgnoreCase(element.getName()) || Constants.SESSION_COOKIE_JSESSIONID.equalsIgnoreCase(element.getName())) { sessionCookie = processCookieHeader(element); } if (customCoookiId != null && customCoookiId.equalsIgnoreCase(element.getName())) { sessionCookie = processCookieHeader(element); } } } // Overwrite old style cookies with new style ones if present cookieHeaders = method.getResponseHeaders(HTTPConstants.HEADER_SET_COOKIE2); for (int i = 0; i < cookieHeaders.length; i++) { HeaderElement[] elements = cookieHeaders[i].getElements(); for (int e = 0; e < elements.length; e++) { HeaderElement element = elements[e]; if (Constants.SESSION_COOKIE.equalsIgnoreCase(element.getName()) || Constants.SESSION_COOKIE_JSESSIONID.equalsIgnoreCase(element.getName())) { sessionCookie = processCookieHeader(element); } if (customCoookiId != null && customCoookiId.equalsIgnoreCase(element.getName())) { sessionCookie = processCookieHeader(element); } } } if (sessionCookie != null) { msgContext.getServiceContext().setProperty(HTTPConstants.COOKIE_STRING, sessionCookie); } }
From source file:org.apache.camel.component.http.HttpPollingConsumer.java
protected Exchange doReceive(int timeout) { Exchange exchange = endpoint.createExchange(); HttpMethod method = createMethod(exchange); // set optional timeout in millis if (timeout > 0) { method.getParams().setSoTimeout(timeout); }// w w w.j a v a 2 s .co m try { // execute request int responseCode = httpClient.executeMethod(method); Object body = HttpHelper.readResponseBodyFromInputStream(method.getResponseBodyAsStream(), exchange); // lets store the result in the output message. Message message = exchange.getOut(); message.setBody(body); // lets set the headers Header[] headers = method.getResponseHeaders(); HeaderFilterStrategy strategy = endpoint.getHeaderFilterStrategy(); for (Header header : headers) { String name = header.getName(); // mapping the content-type if (name.toLowerCase().equals("content-type")) { name = Exchange.CONTENT_TYPE; } String value = header.getValue(); if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) { message.setHeader(name, value); } } message.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode); return exchange; } catch (IOException e) { throw new RuntimeCamelException(e); } finally { method.releaseConnection(); } }
From source file:org.apache.camel.component.http.HttpProducer.java
protected void populateResponse(Exchange exchange, HttpMethod method, Message in, HeaderFilterStrategy strategy, int responseCode) throws IOException, ClassNotFoundException { //We just make the out message is not create when extractResponseBody throws exception, Object response = extractResponseBody(method, exchange); Message answer = exchange.getOut();/*from www.ja v a2 s. c o m*/ answer.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode); answer.setBody(response); // propagate HTTP response headers Header[] headers = method.getResponseHeaders(); for (Header header : headers) { String name = header.getName(); String value = header.getValue(); if (name.toLowerCase().equals("content-type")) { name = Exchange.CONTENT_TYPE; } // use http helper to extract parameter value as it may contain multiple values Object extracted = HttpHelper.extractHttpParameterValue(value); if (strategy != null && !strategy.applyFilterToExternalHeaders(name, extracted, exchange)) { HttpHelper.appendHeader(answer.getHeaders(), name, extracted); } } // preserve headers from in by copying any non existing headers // to avoid overriding existing headers with old values MessageHelper.copyHeaders(exchange.getIn(), answer, false); }
From source file:org.apache.camel.component.http.HttpProducer.java
protected Exception populateHttpOperationFailedException(Exchange exchange, HttpMethod method, int responseCode) throws IOException, ClassNotFoundException { Exception answer;/*from w w w. ja va 2 s . c o m*/ String uri = method.getURI().toString(); String statusText = method.getStatusLine() != null ? method.getStatusLine().getReasonPhrase() : null; Map<String, String> headers = extractResponseHeaders(method.getResponseHeaders()); Object responseBody = extractResponseBody(method, exchange); if (transferException && responseBody != null && responseBody instanceof Exception) { // if the response was a serialized exception then use that return (Exception) responseBody; } // make a defensive copy of the response body in the exception so its detached from the cache String copy = null; if (responseBody != null) { copy = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, responseBody); } if (responseCode >= 300 && responseCode < 400) { String redirectLocation; Header locationHeader = method.getResponseHeader("location"); if (locationHeader != null) { redirectLocation = locationHeader.getValue(); answer = new HttpOperationFailedException(uri, responseCode, statusText, redirectLocation, headers, copy); } else { // no redirect location answer = new HttpOperationFailedException(uri, responseCode, statusText, null, headers, copy); } } else { // internal server error (error code 500) answer = new HttpOperationFailedException(uri, responseCode, statusText, null, headers, copy); } return answer; }
From source file:org.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet.java
/** * Download link and have it be the response. * @param req the http request//www . j a v a2s . co m * @param resp the http response * @param link the link to download * @param c the cookie to set if any * @throws IOException on any error. */ private static void proxyLink(HttpServletRequest req, HttpServletResponse resp, URI link, Cookie c, String proxyHost) throws IOException { org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(link.toString(), false); HttpClientParams params = new HttpClientParams(); params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); HttpClient client = new HttpClient(params); // Make sure we send the request from the proxy address in the config // since that is what the AM filter checks against. IP aliasing or // similar could cause issues otherwise. HostConfiguration config = new HostConfiguration(); InetAddress localAddress = InetAddress.getByName(proxyHost); if (LOG.isDebugEnabled()) { LOG.debug("local InetAddress for proxy host: " + localAddress.toString()); } config.setLocalAddress(localAddress); HttpMethod method = new GetMethod(uri.getEscapedURI()); @SuppressWarnings("unchecked") Enumeration<String> names = req.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); if (passThroughHeaders.contains(name)) { String value = req.getHeader(name); LOG.debug("REQ HEADER: " + name + " : " + value); method.setRequestHeader(name, value); } } String user = req.getRemoteUser(); if (user != null && !user.isEmpty()) { method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII")); } OutputStream out = resp.getOutputStream(); try { resp.setStatus(client.executeMethod(config, method)); for (Header header : method.getResponseHeaders()) { resp.setHeader(header.getName(), header.getValue()); } if (c != null) { resp.addCookie(c); } InputStream in = method.getResponseBodyAsStream(); if (in != null) { IOUtils.copyBytes(in, out, 4096, true); } } finally { method.releaseConnection(); } }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java
/** * Gets the ResponseHeaders//from w w w. j a v a2s . co m * * @param method the method used to perform the request * @return string containing the headers, one per line */ protected String getResponseHeaders(HttpMethod method) { StringBuilder headerBuf = new StringBuilder(); org.apache.commons.httpclient.Header[] rh = method.getResponseHeaders(); headerBuf.append(method.getStatusLine());// header[0] is not the status line... headerBuf.append("\n"); // $NON-NLS-1$ for (Header responseHeader : rh) { String key = responseHeader.getName(); headerBuf.append(key); headerBuf.append(": "); // $NON-NLS-1$ headerBuf.append(responseHeader.getValue()); headerBuf.append("\n"); // $NON-NLS-1$ } return headerBuf.toString(); }
From source file:org.apache.ode.axis2.httpbinding.HttpHelper.java
public static String responseToString(HttpMethod m) { StringBuilder sb = new StringBuilder(256); try {/*from w ww . j a va 2s . c om*/ sb.append("HTTP Response Details: \n").append(m.getName()).append(" ").append(m.getURI()); } catch (URIException e) { // not that important if (log.isDebugEnabled()) log.debug(e); } sb.append("\nStatus-Line: ").append(m.getStatusLine()); Header[] headers = m.getResponseHeaders(); if (headers.length != 0) sb.append("\nResponse Headers: "); for (int i = 0; i < headers.length; i++) { Header h = headers[i]; sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue()); } try { if (StringUtils.isNotEmpty(m.getResponseBodyAsString())) { sb.append("\nResponse Entity:\n").append(m.getResponseBodyAsString()); } } catch (IOException e) { log.error(e); } Header[] footers = m.getResponseFooters(); if (footers.length != 0) sb.append("\nResponse Footers: "); for (int i = 0; i < footers.length; i++) { Header h = footers[i]; sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue()); } return sb.toString(); }
From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java
/** * Process the HTTP Response Headers./*from w ww . ja v a2 s . c o m*/ * <p/> * First go through the list of {@linkplain Namespaces.ODE_HTTP_EXTENSION_NS}{@code :header} elements included in the output binding. * For each of them, set the header value as the value of the message part. * <p/> * Then add all HTTP headers as header part in the message. The name of the header would be the part name. * <p/> * Finally, insert a header names 'Status-Line'. This header contains an element as returned by {@link HttpHelper#statusLineToElement(String)} . * * @param odeMessage * @param method * @param operationDef */ public void extractHttpResponseHeaders(org.apache.ode.bpel.iapi.Message odeMessage, HttpMethod method, Operation operationDef) { Message messageDef = operationDef.getOutput().getMessage(); BindingOutput outputBinding = binding.getBindingOperation(operationDef.getName(), operationDef.getInput().getName(), operationDef.getOutput().getName()).getBindingOutput(); Collection<UnknownExtensibilityElement> headerBindings = WsdlUtils .getHttpHeaders(outputBinding.getExtensibilityElements()); // iterate through the list of header bindings // and set the message parts accordingly for (Iterator<UnknownExtensibilityElement> iterator = headerBindings.iterator(); iterator.hasNext();) { Element binding = iterator.next().getElement(); String partName = binding.getAttribute("part"); String headerName = binding.getAttribute("name"); Part part = messageDef.getPart(partName); if (StringUtils.isNotEmpty(partName)) { Header responseHeader = method.getResponseHeader(headerName); // if the response header is not set, just skip it. no need to fail. if (responseHeader != null) { odeMessage.setPart(partName, createPartElement(part, responseHeader.getValue())); } } else { String errMsg = "Invalid binding: missing required attribute! Part name: " + new QName(Namespaces.ODE_HTTP_EXTENSION_NS, "part"); if (log.isErrorEnabled()) log.error(errMsg); throw new RuntimeException(errMsg); } } // add all HTTP response headers (in their condensed form) into the message as header parts Set<String> headerNames = new HashSet<String>(); for (Header header : method.getResponseHeaders()) headerNames.add(header.getName()); for (String hname : headerNames) odeMessage.setHeaderPart(hname, method.getResponseHeader(hname).getValue()); // make the status line information available as a single element odeMessage.setHeaderPart("Status-Line", HttpHelper.statusLineToElement(method.getStatusLine())); }
From source file:org.apache.servicemix.http.processors.ProviderProcessor.java
protected Map<String, String> getHeaders(HttpMethod method) { Map<String, String> headers = new HashMap<String, String>(); Header[] h = method.getResponseHeaders(); for (int i = 0; i < h.length; i++) { headers.put(h[i].getName(), h[i].getValue()); }/*from w w w.j a v a 2s . c o m*/ return headers; }
From source file:org.attribyte.api.http.impl.commons.Commons3Client.java
@Override public Response send(Request request, RequestOptions options) throws IOException { HttpMethod method = null; switch (request.getMethod()) { case GET:/*from w w w. ja v a2s .c o m*/ method = new GetMethod(request.getURI().toString()); method.setFollowRedirects(options.followRedirects); break; case DELETE: method = new DeleteMethod(request.getURI().toString()); break; case HEAD: method = new HeadMethod(request.getURI().toString()); method.setFollowRedirects(options.followRedirects); break; case POST: method = new PostMethod(request.getURI().toString()); if (request.getBody() != null) { ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(request.getBody().toByteArray()); ((EntityEnclosingMethod) method).setRequestEntity(requestEntity); } else { PostMethod postMethod = (PostMethod) method; Collection<Parameter> parameters = request.getParameters(); for (Parameter parameter : parameters) { String[] values = parameter.getValues(); for (String value : values) { postMethod.addParameter(parameter.getName(), value); } } } break; case PUT: method = new PutMethod(request.getURI().toString()); if (request.getBody() != null) { ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(request.getBody().toByteArray()); ((EntityEnclosingMethod) method).setRequestEntity(requestEntity); } break; } if (userAgent != null && Strings.isNullOrEmpty(request.getHeaderValue("User-Agent"))) { method.setRequestHeader("User-Agent", userAgent); } Collection<Header> headers = request.getHeaders(); for (Header header : headers) { String[] values = header.getValues(); for (String value : values) { method.setRequestHeader(header.getName(), value); } } int responseCode; InputStream is = null; try { responseCode = httpClient.executeMethod(method); is = method.getResponseBodyAsStream(); if (is != null) { byte[] body = Request.bodyFromInputStream(is, options.maxResponseBytes); ResponseBuilder builder = new ResponseBuilder(); builder.setStatusCode(responseCode); builder.addHeaders(getMap(method.getResponseHeaders())); return builder.setBody(body.length != 0 ? body : null).create(); } else { ResponseBuilder builder = new ResponseBuilder(); builder.setStatusCode(responseCode); builder.addHeaders(getMap(method.getResponseHeaders())); return builder.create(); } } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { //Ignore } } method.releaseConnection(); } }