List of usage examples for org.apache.commons.httpclient HttpMethod getResponseHeaders
public abstract Header[] getResponseHeaders();
From source file:org.mozilla.zest.impl.ZestBasicRunner.java
private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException { HttpMethod method; URI uri = new URI(req.getUrl().toString(), false); switch (req.getMethod()) { case "GET": method = new GetMethod(uri.toString()); // Can only redirect on GETs method.setFollowRedirects(req.isFollowRedirects()); break;// w w w . j a v a 2 s .c om case "POST": method = new PostMethod(uri.toString()); break; case "OPTIONS": method = new OptionsMethod(uri.toString()); break; case "HEAD": method = new HeadMethod(uri.toString()); break; case "PUT": method = new PutMethod(uri.toString()); break; case "DELETE": method = new DeleteMethod(uri.toString()); break; case "TRACE": method = new TraceMethod(uri.toString()); break; default: throw new IllegalArgumentException("Method not supported: " + req.getMethod()); } setHeaders(method, req.getHeaders()); for (Cookie cookie : req.getCookies()) { // Replace any Zest variables in the value cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false)); httpclient.getState().addCookie(cookie); } if (req.getMethod().equals("POST")) { // The setRequestEntity call trashes any Content-Type specified, so record it and reapply it after Header contentType = method.getRequestHeader("Content-Type"); RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null); ((PostMethod) method).setRequestEntity(requestEntity); if (contentType != null) { method.setRequestHeader(contentType); } } int code = 0; String responseHeader = null; String responseBody = null; Date start = new Date(); try { this.debug(req.getMethod() + " : " + req.getUrl()); code = httpclient.executeMethod(method); responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders()); responseBody = method.getResponseBodyAsString(); } finally { method.releaseConnection(); } // Update the headers with the ones actually sent req.setHeaders(arrayToStr(method.getRequestHeaders())); if (method.getStatusCode() == 302 && req.isFollowRedirects() && !req.getMethod().equals("GET")) { // Follow the redirect 'manually' as the httpclient lib only supports them for GET requests method = new GetMethod(method.getResponseHeader("Location").getValue()); // Just in case there are multiple redirects method.setFollowRedirects(req.isFollowRedirects()); try { this.debug(req.getMethod() + " : " + req.getUrl()); code = httpclient.executeMethod(method); responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders()); responseBody = method.getResponseBodyAsString(); } finally { method.releaseConnection(); } } return new ZestResponse(req.getUrl(), responseHeader, responseBody, code, new Date().getTime() - start.getTime()); }
From source file:org.mule.transport.as2.As2MuleMessageFactory.java
@Override protected void addProperties(DefaultMuleMessage message, Object transportMessage) throws Exception { String method;//from www . j a va 2 s.c o m HttpVersion httpVersion; String uri; String statusCode = null; Map<String, Object> headers; Map<String, Object> httpHeaders = new HashMap<String, Object>(); Map<String, Object> queryParameters = new HashMap<String, Object>(); if (transportMessage instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) transportMessage; method = httpRequest.getRequestLine().getMethod(); httpVersion = httpRequest.getRequestLine().getHttpVersion(); uri = httpRequest.getRequestLine().getUri(); headers = convertHeadersToMap(httpRequest.getHeaders(), uri); convertMultiPartHeaders(headers); } else if (transportMessage instanceof HttpMethod) { HttpMethod httpMethod = (HttpMethod) transportMessage; method = httpMethod.getName(); httpVersion = HttpVersion.parse(httpMethod.getStatusLine().getHttpVersion()); uri = httpMethod.getURI().toString(); statusCode = String.valueOf(httpMethod.getStatusCode()); headers = convertHeadersToMap(httpMethod.getResponseHeaders(), uri); } else { // This should never happen because of the supported type checking in our superclass throw new MessageTypeNotSupportedException(transportMessage, getClass()); } rewriteConnectionAndKeepAliveHeaders(headers); headers = processIncomingHeaders(headers); httpHeaders.put(HttpConnector.HTTP_HEADERS, new HashMap<String, Object>(headers)); String encoding = getEncoding(headers); queryParameters.put(HttpConnector.HTTP_QUERY_PARAMS, processQueryParams(uri, encoding)); //Make any URI params available ans inbound message headers addUriParamsAsHeaders(headers, uri); headers.put(HttpConnector.HTTP_METHOD_PROPERTY, method); headers.put(HttpConnector.HTTP_REQUEST_PROPERTY, uri); headers.put(HttpConnector.HTTP_VERSION_PROPERTY, httpVersion.toString()); if (enableCookies) { headers.put(HttpConnector.HTTP_COOKIE_SPEC_PROPERTY, cookieSpec); } if (statusCode != null) { headers.put(HttpConnector.HTTP_STATUS_PROPERTY, statusCode); } message.addInboundProperties(headers); message.addInboundProperties(httpHeaders); message.addInboundProperties(queryParameters); // The encoding is stored as message property. To avoid overriding it from the message // properties, it must be initialized last initEncoding(message, encoding); }
From source file:org.mule.transport.http.HttpMuleMessageFactoryTestCase.java
private HttpMethod createMockHttpMethod(String method, InputStream body, String uri, Header[] headers) throws Exception { HttpMethod httpMethod = mock(HttpMethod.class); when(httpMethod.getName()).thenReturn(method); when(httpMethod.getStatusLine()).thenReturn(new StatusLine("HTTP/1.1 200 OK")); when(httpMethod.getStatusCode()).thenReturn(HttpConstants.SC_OK); when(httpMethod.getURI()).thenReturn(new URI(uri, false)); when(httpMethod.getResponseHeaders()).thenReturn(headers); when(httpMethod.getResponseBodyAsStream()).thenReturn(body); return httpMethod; }
From source file:org.mule.transport.http.transformers.HttpClientMethodResponseToObject.java
@Override public Object doTransform(Object src, String encoding) throws TransformerException { Object msg;//from w w w. j a va 2 s . com HttpMethod httpMethod = (HttpMethod) src; InputStream is; try { is = httpMethod.getResponseBodyAsStream(); } catch (IOException e) { throw new TransformerException(this, e); } if (is == null) { msg = NullPayload.getInstance(); } else { msg = new ReleasingInputStream(is, httpMethod); } // Standard headers Map headerProps = new HashMap(); Header[] headers = httpMethod.getResponseHeaders(); String name; for (int i = 0; i < headers.length; i++) { name = headers[i].getName(); if (name.startsWith(HttpConstants.X_PROPERTY_PREFIX)) { name = name.substring(2); } headerProps.put(name, headers[i].getValue()); } // Set Mule Properties return new DefaultMuleMessage(msg, headerProps, muleContext); }
From source file:org.nunux.poc.portal.ProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link HttpServletResponse} * * @param httpMethodProxyRequest An object representing the proxy request to * be made//from ww w . j a v a 2s .c o m * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has * occurred */ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { if (httpServletRequest.isSecure()) { Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443)); } // Create a default HttpClient HttpClient httpClient = new HttpClient(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); InputStream response = httpMethodProxyRequest.getResponseBodyAsStream(); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* * 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* * 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); if (followRedirects) { if (stringLocation.contains("jsessionid")) { Cookie cookie = new Cookie("JSESSIONID", stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11)); cookie.setPath("/"); httpServletResponse.addCookie(cookie); //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL"); } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) { Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie"); String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); if (nameValue[0].equalsIgnoreCase("jsessionid")) { httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(), nameValue[1]); debug("redirecting: store jsessionid: " + nameValue[1]); } else { Cookie cookie = new Cookie(nameValue[0], nameValue[1]); cookie.setPath("/"); //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath()); httpServletResponse.addCookie(cookie); } } httpServletResponse.sendRedirect( stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName)); return; } } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked") || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth // proxy servlet does not support chunked encoding } else if (header.getName().equals("Set-Cookie")) { String[] cookieDetails = header.getValue().split(";"); String[] nameValue = cookieDetails[0].split("="); if (nameValue[0].equalsIgnoreCase("jsessionid")) { httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(), nameValue[1]); debug("redirecting: store jsessionid: " + nameValue[1]); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } List<Header> responseHeaders = Arrays.asList(headerArrayResponse); if (isBodyParameterGzipped(responseHeaders)) { debug("GZipped: true"); int length = 0; if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) { String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); intProxyResponseCode = HttpServletResponse.SC_OK; httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz); } else { final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody()); length = bytes.length; response = new ByteArrayInputStream(bytes); } httpServletResponse.setContentLength(length); } // Send the content to the client debug("Received status code: " + intProxyResponseCode, "Response: " + response); //httpServletResponse.getWriter().write(response); copy(response, httpServletResponse.getOutputStream()); }
From source file:org.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java
/** * @param httpMethod// w ww. ja v a 2 s .c o m * @param responseCode * @return A HttpResponse object made by consuming the response of the given * HttpMethod. * @throws java.io.IOException */ private HttpResponse makeResponse(HttpMethod httpMethod, int responseCode) throws IOException { Map<String, String> headers = Maps.newHashMap(); if (httpMethod.getResponseHeaders() != null) { for (Header h : httpMethod.getResponseHeaders()) { headers.put(h.getName(), h.getValue()); } } // The first header is always null here to provide the response body. headers.remove(null); // Find the response stream - the error stream may be valid in cases // where the input stream is not. InputStream responseBodyStream = null; try { responseBodyStream = httpMethod.getResponseBodyAsStream(); } catch (IOException e) { // normal for 401, 403 and 404 responses, for example... } if (responseBodyStream == null) { // Fall back to zero length response. responseBodyStream = new ByteArrayInputStream(ArrayUtils.EMPTY_BYTE_ARRAY); } String encoding = headers.get("Content-Encoding"); // Create the appropriate stream wrapper based on the encoding type. InputStream is = responseBodyStream; if (encoding == null) { is = responseBodyStream; } else if (encoding.equalsIgnoreCase("gzip")) { is = new GZIPInputStream(responseBodyStream); } else if (encoding.equalsIgnoreCase("deflate")) { Inflater inflater = new Inflater(true); is = new InflaterInputStream(responseBodyStream, inflater); } ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int totalBytesRead = 0; int currentBytesRead; while ((currentBytesRead = is.read(buffer)) != -1) { output.write(buffer, 0, currentBytesRead); totalBytesRead += currentBytesRead; if (maxObjSize > 0 && totalBytesRead > maxObjSize) { IOUtils.closeQuietly(is); IOUtils.closeQuietly(output); // Exceeded max # of bytes return HttpResponse.badrequest("Exceeded maximum number of bytes - " + this.maxObjSize); } } return new HttpResponseBuilder().setHttpStatusCode(responseCode).setResponse(output.toByteArray()) .addHeaders(headers).create(); }
From source file:org.obm.caldav.client.AbstractPushTest.java
private synchronized Document doRequest(HttpMethod hm) { Document xml = null;//ww w. j a v a 2 s . c o m try { int ret = hc.executeMethod(hm); Header[] hs = hm.getResponseHeaders(); for (Header h : hs) { System.err.println("head[" + h.getName() + "] => " + h.getValue()); } if (ret == HttpStatus.SC_UNAUTHORIZED) { UsernamePasswordCredentials upc = new UsernamePasswordCredentials(login, password); authenticate = hm.getHostAuthState().getAuthScheme().authenticate(upc, hm); return null; } else if (ret == HttpStatus.SC_OK || ret == HttpStatus.SC_MULTI_STATUS) { InputStream is = hm.getResponseBodyAsStream(); if (is != null) { if ("text/xml".equals(hm.getRequestHeader("Content-Type"))) { xml = DOMUtils.parse(is); DOMUtils.logDom(xml); } else { System.out.println(FileUtils.streamString(is, false)); } } } else { System.err.println("method failed:\n" + hm.getStatusLine() + "\n" + hm.getResponseBodyAsString()); } } catch (Exception e) { e.printStackTrace(); } finally { hm.releaseConnection(); } return xml; }
From source file:org.onebusaway.presentation.impl.ProxyServlet.java
private void executeMethod(HttpMethod method, HttpServletResponse resp) throws ServletException, IOException { HttpClient client = new HttpClient(); int status = client.executeMethod(method); resp.setStatus(status);/*from www .java2 s. c o m*/ // Pass response headers back to the client Header[] headerArrayResponse = method.getResponseHeaders(); for (Header header : headerArrayResponse) resp.setHeader(header.getName(), header.getValue()); // Send the content to the client InputStream in = method.getResponseBodyAsStream(); OutputStream out = resp.getOutputStream(); byte[] buffer = new byte[1024]; int rc; while ((rc = in.read(buffer)) != -1) out.write(buffer, 0, rc); }
From source file:org.owtf.runtime.core.ZestBasicRunner.java
private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException { HttpMethod method; URI uri = new URI(req.getUrl().toString(), false); switch (req.getMethod()) { case "GET": method = new GetMethod(uri.toString()); // Can only redirect on GETs method.setFollowRedirects(req.isFollowRedirects()); break;/*w w w. j av a 2 s .co m*/ case "POST": method = new PostMethod(uri.toString()); break; case "OPTIONS": method = new OptionsMethod(uri.toString()); break; case "HEAD": method = new HeadMethod(uri.toString()); break; case "PUT": method = new PutMethod(uri.toString()); break; case "DELETE": method = new DeleteMethod(uri.toString()); break; case "TRACE": method = new TraceMethod(uri.toString()); break; default: throw new IllegalArgumentException("Method not supported: " + req.getMethod()); } setHeaders(method, req.getHeaders()); for (Cookie cookie : req.getCookies()) { // Replace any Zest variables in the value cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false)); httpclient.getState().addCookie(cookie); } if (req.getMethod().equals("POST")) { // Do this after setting the headers so the length is corrected RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null); ((PostMethod) method).setRequestEntity(requestEntity); } int code = 0; String responseHeader = null; String responseBody = null; Date start = new Date(); try { this.debug(req.getMethod() + " : " + req.getUrl()); code = httpclient.executeMethod(method); responseHeader = method.getStatusLine().toString() + "\n" + arrayToStr(method.getResponseHeaders()); // httpclient.getParams().setParameter("http.method.response.buffer.warnlimit",new Integer(1000000000)); responseBody = method.getResponseBodyAsString(); } finally { method.releaseConnection(); } // Update the headers with the ones actually sent req.setHeaders(arrayToStr(method.getRequestHeaders())); return new ZestResponse(req.getUrl(), responseHeader, responseBody, code, new Date().getTime() - start.getTime()); }
From source file:org.parosproxy.paros.network.HttpMethodHelper.java
private static String getHttpResponseHeaderAsString(HttpMethod httpMethod) { StringBuilder sb = new StringBuilder(200); String name = null;/* w w w. ja v a 2 s . c o m*/ String value = null; // add status line sb.append(httpMethod.getStatusLine().toString()).append(CRLF); Header[] header = httpMethod.getResponseHeaders(); for (int i = 0; i < header.length; i++) { name = header[i].getName(); value = header[i].getValue(); sb.append(name).append(": ").append(value).append(CRLF); } sb.append(CRLF); return sb.toString(); }