List of usage examples for org.apache.commons.httpclient HttpMethod setRequestHeader
public abstract void setRequestHeader(String paramString1, String paramString2);
From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java
public int postDocument(InputStream stream) throws IOException, Exception { HttpClient client = new HttpClient(); HttpMethod method; String urlStr = solrHost + "/update?commit=true"; Log.debug("Ingesting a new document to: " + urlStr); method = new PostMethod(urlStr); RequestEntity entity = new InputStreamRequestEntity(stream); ((PostMethod) method).setRequestEntity(entity); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); method.setRequestHeader("Content-Type", "text/xml"); method.setRequestHeader("charset", "utf-8"); // Execute the method. int statusCode = client.executeMethod(method); SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsStream()); Log.debug(solrResponse.getXMLDocumentString()); if (statusCode != HttpStatus.SC_OK) { Log.error("Method failed: " + method.getStatusLine()); Log.error(solrResponse.getXMLDocumentString()); } else//w w w .ja va2 s .c o m Log.debug(solrResponse.getXMLDocumentString()); return statusCode; }
From source file:com.mercatis.lighthouse3.commons.commons.HttpRequest.java
/** * This method performs an HTTP request against an URL. * * @param url the URL to call/*from ww w . j a v a 2s . c o m*/ * @param method the HTTP method to execute * @param body the body of a POST or PUT request, can be <code>null</code> * @param queryParams a Hash with the query parameter, can be <code>null</code> * @return the data returned by the web server * @throws HttpException in case a communication error occurred. */ @SuppressWarnings("deprecation") public String execute(String url, HttpRequest.HttpMethod method, String body, Map<String, String> queryParams) { NameValuePair[] query = null; if (queryParams != null) { query = new NameValuePair[queryParams.size()]; int counter = 0; for (Entry<String, String> queryParam : queryParams.entrySet()) { query[counter] = new NameValuePair(queryParam.getKey(), queryParam.getValue()); counter++; } } org.apache.commons.httpclient.HttpMethod request = null; if (method == HttpMethod.GET) { request = new GetMethod(url); } else if (method == HttpMethod.POST) { PostMethod postRequest = new PostMethod(url); if (body != null) { postRequest.setRequestBody(body); } request = postRequest; } else if (method == HttpMethod.PUT) { PutMethod putRequest = new PutMethod(url); if (body != null) { putRequest.setRequestBody(body); } request = putRequest; } else if (method == HttpMethod.DELETE) { request = new DeleteMethod(url); } request.setRequestHeader("Content-type", "application/xml;charset=utf-8"); if (query != null) { request.setQueryString(query); } int resultCode = 0; StringBuilder resultBodyBuilder = new StringBuilder(); try { resultCode = this.httpClient.executeMethod(request); BufferedReader reader = new BufferedReader( new InputStreamReader(request.getResponseBodyAsStream(), Charset.forName("UTF-8"))); String line = null; while ((line = reader.readLine()) != null) { resultBodyBuilder.append(line); } if (resultCode != 200) { throw new HttpException(resultBodyBuilder.toString(), null); } } catch (HttpException httpException) { throw new HttpException("HTTP request failed", httpException); } catch (IOException ioException) { throw new HttpException("HTTP request failed", ioException); } catch (NullPointerException npe) { throw new HttpException("HTTP request failed", npe); } finally { request.releaseConnection(); } return resultBodyBuilder.toString(); }
From source file:com.sun.syndication.fetcher.impl.HttpClientFeedFetcher.java
/** * @see com.sun.syndication.fetcher.FeedFetcher#retrieveFeed(java.net.URL) *//* w w w .j a va 2s. c om*/ public SyndFeed retrieveFeed(URL feedUrl) throws IllegalArgumentException, IOException, FeedException, FetcherException { if (feedUrl == null) { throw new IllegalArgumentException("null is not a valid URL"); } // TODO Fix this //System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); HttpClient client = new HttpClient(httpClientParams); if (getCredentialSupplier() != null) { client.getState().setAuthenticationPreemptive(true); // TODO what should realm be here? Credentials credentials = getCredentialSupplier().getCredentials(null, feedUrl.getHost()); if (credentials != null) { client.getState().setCredentials(null, feedUrl.getHost(), credentials); } } System.setProperty("httpclient.useragent", getUserAgent()); String urlStr = feedUrl.toString(); HttpMethod method = new GetMethod(urlStr); method.addRequestHeader("Accept-Encoding", "gzip"); method.addRequestHeader("User-Agent", getUserAgent()); method.setFollowRedirects(true); if (httpClientMethodCallback != null) { synchronized (httpClientMethodCallback) { httpClientMethodCallback.afterHttpClientMethodCreate(method); } } FeedFetcherCache cache = getFeedInfoCache(); if (cache != null) { // retrieve feed try { if (isUsingDeltaEncoding()) { method.setRequestHeader("A-IM", "feed"); } // get the feed info from the cache // Note that syndFeedInfo will be null if it is not in the cache SyndFeedInfo syndFeedInfo = cache.getFeedInfo(feedUrl); if (syndFeedInfo != null) { method.setRequestHeader("If-None-Match", syndFeedInfo.getETag()); if (syndFeedInfo.getLastModified() instanceof String) { method.setRequestHeader("If-Modified-Since", (String) syndFeedInfo.getLastModified()); } } int statusCode = client.executeMethod(method); fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr); handleErrorCodes(statusCode); SyndFeed feed = getFeed(syndFeedInfo, urlStr, method, statusCode); syndFeedInfo = buildSyndFeedInfo(feedUrl, urlStr, method, feed, statusCode); cache.setFeedInfo(new URL(urlStr), syndFeedInfo); // the feed may have been modified to pick up cached values // (eg - for delta encoding) feed = syndFeedInfo.getSyndFeed(); return feed; } finally { method.releaseConnection(); method.recycle(); } } else { // cache is not in use try { int statusCode = client.executeMethod(method); fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr); handleErrorCodes(statusCode); return getFeed(null, urlStr, method, statusCode); } finally { method.releaseConnection(); method.recycle(); } } }
From source file:com.sun.socialsite.web.rest.opensocial.ConsumerContext.java
/** * Adds an element to this object's context chain. If the specified * element has a "delegate" attribute, this method will retrieve the * delegation element and recursively add it also. * * @param element the ChainElement to be added to the context chain. *///www. j a v a 2 s .com private void appendToChain(URL source, boolean loadedDirectly, JSONObject contents) throws SocialSiteException { try { ChainElement element = null; if (contents.has("attributes")) { element = new LegacyChainElement(source, loadedDirectly, contents); } else { element = new ChainElement(source, loadedDirectly, contents); } elements.add(element); if (element.contents.has("delegate")) { JSONObject delegate = element.contents.getJSONObject("delegate"); URL url = null; if (element.source != null) { url = new URL(element.source, delegate.getString("url")); } else { url = new URL(delegate.getString("url")); } HttpClient httpClient = new HttpClient(); HttpMethod method = null; if ("GET".equalsIgnoreCase(delegate.getString("method"))) { method = new GetMethod(url.toExternalForm()); } if (delegate.has("headers")) { JSONObject headers = delegate.getJSONObject("headers"); for (Iterator<?> iterator = headers.keys(); iterator.hasNext();) { String name = iterator.next().toString(); String value = headers.get(name).toString(); method.addRequestHeader(name, value); } } if (element.source != null) { method.setRequestHeader("Referer", element.source.toString()); } int responseCode = httpClient.executeMethod(method); if (responseCode == 200) { String responseBody = method.getResponseBodyAsString(); appendToChain(url, true, new JSONObject(responseBody)); if (log.isDebugEnabled()) { String msg = String.format("%s %s returned %d: %s", method.getName(), url, responseCode, responseBody); log.debug(msg); } } else { String msg = String.format("%s %s returned %d", method.getName(), url, responseCode); throw new SocialSiteException(msg); } } } catch (SocialSiteException e) { throw e; } catch (Exception e) { throw new SocialSiteException(e); } }
From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java
/** * Retrieves all of the cookies from the servlet request and sets them on * the proxy request/*from w ww . j a v a2s.c o m*/ * * @param httpServletRequest The request object representing the client's * request to the servlet engine * @param httpMethodProxyRequest The request that we are about to send to * the proxy host */ private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) { // Get an array of all of all the cookies sent by the client Cookie[] cookies = httpServletRequest.getCookies(); if (cookies == null) { return; } for (Cookie cookie : cookies) { cookie.setDomain(stringProxyHost); cookie.setPath(httpServletRequest.getServletPath()); httpMethodProxyRequest.setRequestHeader("Cookie", cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath()); } }
From source file:net.sf.j2ep.requesthandlers.RequestHandlerBase.java
/** * Will write the proxy specific headers such as Via and x-forwarded-for. * /*from w w w .ja va2 s . com*/ * @param method Method to write the headers to * @param request The incoming request, will need to get virtual host. * @throws HttpException */ private void setProxySpecificHeaders(HttpMethod method, HttpServletRequest request) throws HttpException { String serverHostName = "jEasyExtensibleProxy"; try { serverHostName = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { log.error("Couldn't get the hostname needed for headers x-forwarded-server and Via", e); } String originalVia = request.getHeader("via"); StringBuffer via = new StringBuffer(""); if (originalVia != null) { if (originalVia.indexOf(serverHostName) != -1) { log.error("This proxy has already handled the request, will abort."); throw new HttpException("Request has a cyclic dependency on this proxy."); } via.append(originalVia).append(", "); } via.append(request.getProtocol()).append(" ").append(serverHostName); method.setRequestHeader("via", via.toString()); method.setRequestHeader("x-forwarded-for", request.getRemoteAddr()); method.setRequestHeader("x-forwarded-host", request.getServerName()); method.setRequestHeader("x-forwarded-server", serverHostName); method.setRequestHeader("accept-encoding", ""); }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Retrieves all of the cookies from the servlet request and sets them on * the proxy request/*from w w w . j a va 2 s . c o m*/ * * @param httpServletRequest The request object representing the client's * request to the servlet engine * @param httpMethodProxyRequest The request that we are about to send to * the proxy host */ @SuppressWarnings("unchecked") private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) { // Get an array of all of all the cookies sent by the client Cookie[] cookies = httpServletRequest.getCookies(); if (cookies == null) { return; } for (Cookie cookie : cookies) { cookie.setDomain(stringProxyHost); cookie.setPath(httpServletRequest.getServletPath()); httpMethodProxyRequest.setRequestHeader("Cookie", cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath()); } }
From source file:cuanto.api.CuantoConnector.java
/** * @param methodType HTTP_GET or HTTP_POST * @param url The URL for this method to contact * @return The HTTP method configured with the correct User-Agent header. *//*from w w w .j av a 2s .co m*/ private HttpMethod getHttpMethod(String methodType, String url) { HttpMethod method; if (methodType.toLowerCase().equals(HTTP_GET)) { method = new GetMethod(url); } else if (methodType.toLowerCase() == HTTP_POST) { method = new PostMethod(url); } else { throw new RuntimeException("Unknown HTTP method: ${methodType}"); } method.setRequestHeader("User-Agent", HTTP_USER_AGENT); return method; }
From source file:com.basho.riak.client.RiakObject.java
/** * Serializes this object to an existing {@link HttpMethod} which can be * sent as an HTTP request. Specifically, sends the object's link, * user-defined metadata and vclock as HTTP headers and the value as the * body. Used by {@link RiakClient} to create PUT requests. *//*from w w w.ja v a 2 s . co m*/ public void writeToHttpMethod(HttpMethod httpMethod) { // Serialize headers String basePath = getBasePathFromHttpMethod(httpMethod); writeLinks(httpMethod, basePath); for (String name : userMetaData.keySet()) { httpMethod.setRequestHeader(Constants.HDR_USERMETA_REQ_PREFIX + name, userMetaData.get(name)); } if (vclock != null) { httpMethod.setRequestHeader(Constants.HDR_VCLOCK, vclock); } // Serialize body if (httpMethod instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod; // Any value set using setValueAsStream() has precedent over value // set using setValue() if (valueStream != null) { if (valueStreamLength != null && valueStreamLength >= 0) { entityEnclosingMethod.setRequestEntity( new InputStreamRequestEntity(valueStream, valueStreamLength, contentType)); } else { entityEnclosingMethod.setRequestEntity(new InputStreamRequestEntity(valueStream, contentType)); } } else if (value != null) { entityEnclosingMethod.setRequestEntity(new ByteArrayRequestEntity(value, contentType)); } else { entityEnclosingMethod.setRequestEntity(new ByteArrayRequestEntity("".getBytes(), contentType)); } } }
From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java
/** * Retreives all of the headers from the servlet request and sets them on * the proxy request//ww w.j a va 2 s. c om * * @param httpServletRequest The request object representing the client's * request to the servlet engine * @param httpMethodProxyRequest The request that we are about to send to * the proxy host */ @SuppressWarnings("unchecked") private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) { // Get an Enumeration of all of the header names sent by the client Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String stringHeaderName = (String) enumerationOfHeaderNames.nextElement(); if (stringHeaderName.equalsIgnoreCase(HttpConstants.STRING_CONTENT_LENGTH_HEADER_NAME)) continue; // Support gzip transfer encoding if (stringHeaderName.equalsIgnoreCase(HttpConstants.STRING_ACCEPT_ENCODING_HEADER_NAME)) { httpMethodProxyRequest.setRequestHeader(stringHeaderName, "gzip"); continue; } // As per the Java Servlet API 2.5 documentation: // Some headers, such as Accept-Language can be sent by clients // as several headers each with a different value rather than // sending the header as a comma separated list. // Thus, we get an Enumeration of the header values sent by the client Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName); while (enumerationOfHeaderValues.hasMoreElements()) { String stringHeaderValue = (String) enumerationOfHeaderValues.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server //if(stringHeaderName.equalsIgnoreCase(HttpConstants.STRING_HOST_HEADER_NAME)){ // stringHeaderValue = getProxyHostAndPort(); //} Header header = new Header(stringHeaderName, stringHeaderValue); // Set the same header on the proxy request httpMethodProxyRequest.setRequestHeader(header); } } }