List of usage examples for org.apache.commons.httpclient HttpMethod addRequestHeader
public abstract void addRequestHeader(String paramString1, String paramString2);
From source file:org.apache.jackrabbit.spi2dav.RepositoryServiceImpl.java
protected static void initMethod(HttpMethod method, SessionInfo sessionInfo) throws RepositoryException { boolean isReadAccess = readMethods.contains(method.getName()); boolean needsSessionId = !isReadAccess || "POLL".equals(method.getName()); if (sessionInfo instanceof SessionInfoImpl && needsSessionId) { StringBuilder linkHeaderField = new StringBuilder(); String sessionIdentifier = ((SessionInfoImpl) sessionInfo).getSessionIdentifier(); linkHeaderField.append("<").append(sessionIdentifier).append(">; rel=\"") .append(JcrRemotingConstants.RELATION_REMOTE_SESSION_ID).append("\""); String userdata = ((SessionInfoImpl) sessionInfo).getUserData(); if (userdata != null && !isReadAccess) { String escaped = Text.escape(userdata); linkHeaderField.append(", <data:,").append(escaped).append(">; rel=\"") .append(JcrRemotingConstants.RELATION_USER_DATA).append("\""); }//w w w. j ava 2 s. c o m method.addRequestHeader("Link", linkHeaderField.toString()); } }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java
/** * Extracts all the required non-cookie headers for that particular URL request and * sets them in the <code>HttpMethod</code> passed in * * @param method/*from www.j ava 2 s .c om*/ * <code>HttpMethod</code> which represents the request * @param u * <code>URL</code> of the URL request * @param headerManager * the <code>HeaderManager</code> containing all the cookies * for this <code>UrlConfig</code> * @param cacheManager the CacheManager (may be null) */ private void setConnectionHeaders(HttpMethod method, URL u, HeaderManager headerManager, CacheManager cacheManager) { // Set all the headers from the HeaderManager if (headerManager != null) { CollectionProperty headers = headerManager.getHeaders(); if (headers != null) { for (JMeterProperty jMeterProperty : headers) { org.apache.jmeter.protocol.http.control.Header header = (org.apache.jmeter.protocol.http.control.Header) jMeterProperty .getObjectValue(); String n = header.getName(); // Don't allow override of Content-Length // This helps with SoapSampler hack too // TODO - what other headers are not allowed? if (!HTTPConstants.HEADER_CONTENT_LENGTH.equalsIgnoreCase(n)) { String v = header.getValue(); if (HTTPConstants.HEADER_HOST.equalsIgnoreCase(n)) { v = v.replaceFirst(":\\d+$", ""); // remove any port specification // $NON-NLS-1$ $NON-NLS-2$ method.getParams().setVirtualHost(v); } else { method.addRequestHeader(n, v); } } } } } if (cacheManager != null) { cacheManager.setHeaders(u, method); } }
From source file:org.apache.jmeter.protocol.oauth.sampler.OAuthSampler.java
/** * Add Authorization header if useAuthHeader is true. * /*from www . j a v a2 s .c o m*/ * @param httpMethod the HttpMethod used for the request */ protected void setDefaultRequestHeaders(HttpMethod httpMethod) { if (!useAuthHeader) return; try { httpMethod.addRequestHeader("Authorization", message //$NON-NLS-1$ .getAuthorizationHeader(null)); } catch (IOException e) { log.error("Failed to set Authorization header: " + e.getMessage()); //$NON-NLS-1$ } }
From source file:org.apache.jmeter.protocol.oauth.sampler.OAuthSampler.java
private String sendPostData(HttpMethod method) throws IOException { String form;//from w w w.jav a 2s .co m if (useAuthHeader) { form = OAuth.formEncode(nonOAuthParams); } else { form = OAuth.formEncode(message.getParameters()); } method.addRequestHeader(HEADER_CONTENT_TYPE, OAuth.FORM_ENCODED); method.addRequestHeader(HEADER_CONTENT_LENGTH, form.length() + ""); //$NON-NLS-1$ if (method instanceof PostMethod || method instanceof PutMethod) { StringRequestEntity requestEntity = new StringRequestEntity(form, OAuth.FORM_ENCODED, OAuth.ENCODING); ((EntityEnclosingMethod) method).setRequestEntity(requestEntity); } else { log.error("Logic error, method must be POST or PUT to send body"); //$NON-NLS-1$ } return form; }
From source file:org.apache.kylin.engine.mr.common.HadoopStatusGetter.java
private String getHttpResponse(String url) throws IOException { HttpClient client = new HttpClient(); String response = null;/*from w w w .j av a 2 s. c om*/ while (response == null) { // follow redirects via 'refresh' if (url.startsWith("https://")) { registerEasyHttps(); } if (url.contains("anonymous=true") == false) { url += url.contains("?") ? "&" : "?"; url += "anonymous=true"; } HttpMethod get = new GetMethod(url); get.addRequestHeader("accept", "application/json"); try { client.executeMethod(get); String redirect = null; Header h = get.getResponseHeader("Location"); if (h != null) { redirect = h.getValue(); if (isValidURL(redirect) == false) { logger.info("Get invalid redirect url, skip it: " + redirect); Thread.sleep(1000L); continue; } } else { h = get.getResponseHeader("Refresh"); if (h != null) { String s = h.getValue(); int cut = s.indexOf("url="); if (cut >= 0) { redirect = s.substring(cut + 4); if (isValidURL(redirect) == false) { logger.info("Get invalid redirect url, skip it: " + redirect); Thread.sleep(1000L); continue; } } } } if (redirect == null) { response = get.getResponseBodyAsString(); logger.debug("Job " + mrJobId + " get status check result.\n"); } else { url = redirect; logger.debug("Job " + mrJobId + " check redirect url " + url + ".\n"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error(e.getMessage()); } finally { get.releaseConnection(); } } return response; }
From source file:org.apache.kylin.tool.JobTaskCounterExtractor.java
private String getHttpResponse(String url) { HttpClient client = new HttpClient(); String response = null;//from ww w . jav a 2 s .c om while (response == null) { HttpMethod get = new GetMethod(url); try { get.addRequestHeader("accept", "application/json"); client.executeMethod(get); response = get.getResponseBodyAsString(); } catch (Exception e) { logger.warn("Failed to fetch http response" + e); } finally { get.releaseConnection(); } } return response; }
From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java
protected void setHeaders(HttpMethod method) { HttpMethodConfiguration config = httpConfiguration == null ? null : httpConfiguration.getMethodConfiguration(method); if (config == null || config.isUseDefaultHeaders()) { // TODO: merge with the other headers and have some better defaults, unify with lightweight headers method.addRequestHeader("Cache-control", "no-cache"); method.addRequestHeader("Cache-store", "no-store"); method.addRequestHeader("Pragma", "no-cache"); method.addRequestHeader("Expires", "0"); method.addRequestHeader("Accept-Encoding", "gzip"); }//from w ww . j ava2s .co m if (httpHeaders != null) { for (Object header : httpHeaders.keySet()) { method.addRequestHeader((String) header, httpHeaders.getProperty((String) header)); } } Header[] headers = config == null ? null : config.asRequestHeaders(); if (headers != null) { for (Header header : headers) { method.addRequestHeader(header); } } }
From source file:org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.java
protected void setHeaders(HttpMethod method) { HttpMethodConfiguration config = httpConfiguration == null ? null : httpConfiguration.getMethodConfiguration(method); if (config == null || config.isUseDefaultHeaders()) { // TODO: merge with the other headers and have some better defaults, unify with lightweight headers method.addRequestHeader("Cache-control", "no-cache"); method.addRequestHeader("Cache-store", "no-store"); method.addRequestHeader("Pragma", "no-cache"); method.addRequestHeader("Expires", "0"); method.addRequestHeader("Accept-Encoding", "gzip"); }/*from w w w . j a v a 2s . c om*/ if (httpHeaders != null) { for (Iterator i = httpHeaders.keySet().iterator(); i.hasNext();) { String header = (String) i.next(); method.addRequestHeader(header, httpHeaders.getProperty(header)); } } Header[] headers = config == null ? null : config.asRequestHeaders(); if (headers != null) { for (int i = 0; i < headers.length; i++) { method.addRequestHeader(headers[i]); } } }
From source file:org.apache.sling.commons.testing.integration.TestInfoPassingClient.java
/** * Adds all MDC key-value pairs as HTTP header where the key starts * with 'X-Sling-'//from w w w. ja v a2 s .c om */ private static void addSlingHeaders(HttpMethod m) { Map<?, ?> mdc = MDC.getCopyOfContextMap(); if (mdc != null) { for (Map.Entry<?, ?> e : mdc.entrySet()) { Object key = e.getKey(); if (key instanceof String && ((String) key).startsWith(SLING_HEADER_PREFIX) && e.getValue() instanceof String) { m.addRequestHeader((String) key, (String) e.getValue()); } } } }
From source file:org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.java
public NamedList<Object> request(final SolrRequest request, ResponseParser processor) throws SolrServerException, IOException { HttpMethod method = null; InputStream is = null;//w w w .ja v a2s .c om SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = "/select"; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = _parser; } // The parser 'wt=' and 'version=' params are used instead of the original params ModifiableSolrParams wparams = new ModifiableSolrParams(); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (params == null) { params = wparams; } else { params = new DefaultSolrParams(wparams, params); } if (_invariantParams != null) { params = new DefaultSolrParams(_invariantParams, params); } int tries = _maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = _baseURL + path; boolean isMultipart = (streams != null && streams.size() > 1); if (streams == null || isMultipart) { PostMethod post = new PostMethod(url); post.getParams().setContentCharset("UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (this.useMultiPartPost || isMultipart) { parts.add(new StringPart(p, v, "UTF-8")); } else { post.addParameter(p, v); } } } } if (isMultipart) { int i = 0; for (ContentStream content : streams) { final ContentStream c = content; String charSet = null; PartSource source = new PartSource() { public long getLength() { return c.getSize(); } public String getFileName() { return c.getName(); } public InputStream createInputStream() throws IOException { return c.getStream(); } }; parts.add(new FilePart(c.getName(), source, c.getContentType(), charSet)); } } if (parts.size() > 0) { post.setRequestEntity(new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), post.getParams())); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(params, false); PostMethod post = new PostMethod(url + pstr); // post.setRequestHeader("connection", "close"); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setRequestEntity(new RequestEntity() { public long getContentLength() { return -1; } public String getContentType() { return contentStream[0].getContentType(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream outputStream) throws IOException { ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream); } }); } else { is = contentStream[0].getStream(); post.setRequestEntity( new InputStreamRequestEntity(is, contentStream[0].getContentType())); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { // This is generally safe to retry on method.releaseConnection(); method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if ((tries < 1)) { throw r; } //log.warn( "Caught: " + r + ". Retrying..." ); } } } catch (IOException ex) { log.error("####request####", ex); throw new SolrServerException("error reading streams", ex); } method.setFollowRedirects(_followRedirects); method.addRequestHeader("User-Agent", AGENT); if (_allowCompression) { method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate")); } // method.setRequestHeader("connection", "close"); try { // Execute the method. //System.out.println( "EXECUTE:"+method.getURI() ); int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { StringBuilder msg = new StringBuilder(); msg.append(method.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append(method.getStatusText()); msg.append("\n\n"); msg.append("request: " + method.getURI()); throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8")); } // Read the contents String charset = "UTF-8"; if (method instanceof HttpMethodBase) { charset = ((HttpMethodBase) method).getResponseCharSet(); } InputStream respBody = method.getResponseBodyAsStream(); // Jakarta Commons HTTPClient doesn't handle any // compression natively. Handle gzip or deflate // here if applicable. if (_allowCompression) { Header contentEncodingHeader = method.getResponseHeader("Content-Encoding"); if (contentEncodingHeader != null) { String contentEncoding = contentEncodingHeader.getValue(); if (contentEncoding.contains("gzip")) { //log.debug( "wrapping response in GZIPInputStream" ); respBody = new GZIPInputStream(respBody); } else if (contentEncoding.contains("deflate")) { //log.debug( "wrapping response in InflaterInputStream" ); respBody = new InflaterInputStream(respBody); } } else { Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader.getValue(); if (contentType != null) { if (contentType.startsWith("application/x-gzip-compressed")) { //log.debug( "wrapping response in GZIPInputStream" ); respBody = new GZIPInputStream(respBody); } else if (contentType.startsWith("application/x-deflate")) { //log.debug( "wrapping response in InflaterInputStream" ); respBody = new InflaterInputStream(respBody); } } } } } return processor.processResponse(respBody, charset); } catch (HttpException e) { throw new SolrServerException(e); } catch (IOException e) { throw new SolrServerException(e); } finally { method.releaseConnection(); if (is != null) { is.close(); } } }