List of usage examples for org.apache.commons.httpclient HttpMethod getRequestHeaders
public abstract Header[] getRequestHeaders();
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java
/** * Get all the request headers for the <code>HttpMethod</code> * * @param method//from ww w. j a va 2 s. c o m * <code>HttpMethod</code> which represents the request * @return the headers as a string */ protected String getConnectionHeaders(HttpMethod method) { // Get all the request headers StringBuilder hdrs = new StringBuilder(100); Header[] requestHeaders = method.getRequestHeaders(); for (Header requestHeader : requestHeaders) { // Exclude the COOKIE header, since cookie is reported separately in the sample if (!HTTPConstants.HEADER_COOKIE.equalsIgnoreCase(requestHeader.getName())) { hdrs.append(requestHeader.getName()); hdrs.append(": "); // $NON-NLS-1$ hdrs.append(requestHeader.getValue()); hdrs.append("\n"); // $NON-NLS-1$ } } return hdrs.toString(); }
From source file:org.apache.ode.axis2.httpbinding.HttpHelper.java
public static String requestToString(HttpMethod m) { StringBuilder sb = new StringBuilder(256); try {/* ww w.java 2 s .c o m*/ sb.append("HTTP Request Details: \n").append(m.getName()).append(" ").append(m.getURI()); } catch (URIException e) { // not that important if (log.isDebugEnabled()) log.debug(e); } sb.append("\nRequest Headers:"); Header[] headers = m.getRequestHeaders(); if (headers.length == 0) sb.append(" n/a"); for (int i = 0; i < headers.length; i++) { Header h = headers[i]; sb.append("\n\t").append(h.getName()).append(": ").append(h.getValue()); } if (m instanceof EntityEnclosingMethod) { EntityEnclosingMethod eem = (EntityEnclosingMethod) m; if (eem.getRequestEntity() != null) { sb.append("\nRequest Entity:"); sb.append("\n\tContent-Type:").append(eem.getRequestEntity().getContentType()); sb.append("\n\tContent-Length:").append(eem.getRequestEntity().getContentLength()); if (eem.getRequestEntity() instanceof StringRequestEntity) { StringRequestEntity sre = (StringRequestEntity) eem.getRequestEntity(); sb.append("\n\tContent-Charset:").append(sre.getCharset()); sb.append("\n\tRequest Entity:\n").append(sre.getContent()); } } } return sb.toString(); }
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:// www .j ava 2 s .c o m 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.j2free.http.HttpCallResult.java
/** * /* w w w. ja va 2 s. co m*/ * @param method * @throws IOException */ public HttpCallResult(HttpMethod method) throws IOException { this.method = method; this.response = method.getResponseBodyAsString(); this.bytes = method.getResponseBody(); requestHeaders = new HashMap(); responseHeaders = new HashMap(); Header[] headers = method.getRequestHeaders(); for (Header header : headers) { requestHeaders.put(header.getName(), header); } headers = method.getResponseHeaders(); for (Header header : headers) { responseHeaders.put(header.getName(), header); } status = method.getStatusLine(); }
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;/*from www . j a v a 2 s .com*/ 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.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;//from w w w. j ava 2 s . c o 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
public static void updateHttpRequestHeaderSent(HttpRequestHeader req, HttpMethod httpMethodSent) { // Not used yet, no need to update request. if (!httpMethodSent.hasBeenUsed()) { return;//ww w . j a v a 2s . c o m } StringBuilder sb = new StringBuilder(200); String name = null; String value = null; // add status line sb.append(req.getPrimeHeader()).append(CRLF); Header[] header = httpMethodSent.getRequestHeaders(); 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); try { req.setMessage(sb.toString()); } catch (HttpMalformedHeaderException e) { logger.error(e.getMessage(), e); } }
From source file:org.switchyard.component.test.mixins.http.HTTPMixIn.java
/** * Execute the supplied HTTP Method./* w w w . j a v a2s .co m*/ * <p/> * Does not release the {@link org.apache.commons.httpclient.HttpMethod#releaseConnection() HttpMethod connection}. * * @param method The HTTP Method. * @return The HTTP Response. */ public String execute(HttpMethod method) { if (_httpClient == null) { Assert.fail( "HTTPMixIn not initialized. You must call the initialize() method before using this MixIn"); } for (String key : _requestHeaders.keySet()) { method.setRequestHeader(key, _requestHeaders.get(key)); } if (_dumpMessages) { for (Header header : method.getRequestHeaders()) { _logger.info("Request header:[" + header.getName() + "=" + header.getValue() + "]"); } } String response = null; try { _httpClient.executeMethod(method); response = method.getResponseBodyAsString(); } catch (Exception e) { try { Assert.fail("Exception invoking HTTP endpoint '" + method.getURI() + "': " + e.getMessage()); } catch (URIException e1) { _logger.error("Unexpected error", e1); return null; } } if (_dumpMessages) { for (Header header : method.getResponseHeaders()) { _logger.info("Received response header:[" + header.getName() + "=" + header.getValue() + "]"); } _logger.info("Received response body:[" + response + "]"); } for (String key : _expectedHeaders.keySet()) { Header actual = method.getResponseHeader(key); Assert.assertNotNull("Checking response header:[" + key + "]", actual); Assert.assertEquals("Checking response header:[" + key + "]", _expectedHeaders.get(key), actual.getValue()); } return response; }
From source file:org.tuleap.mylyn.task.core.tests.internal.client.rest.MockRestConnector.java
protected ServerRequest getServerRequest(HttpMethod method) { Map<String, String> header = new LinkedHashMap<String, String>(); for (Header h : method.getRequestHeaders()) { header.put(h.getName(), h.getValue()); }//from ww w . j av a2 s. c om if (method instanceof EntityEnclosingMethod) { RequestEntity entity = ((EntityEnclosingMethod) method).getRequestEntity(); if (entity instanceof StringRequestEntity) { return new ServerRequest(method.getName(), method.getPath(), header, method.getQueryString(), ((StringRequestEntity) entity).getContent()); } } return new ServerRequest(method.getName(), method.getPath(), header, method.getQueryString()); }