List of usage examples for org.apache.commons.httpclient HttpMethod addRequestHeader
public abstract void addRequestHeader(String paramString1, String paramString2);
From source file:net.sf.j2ep.requesthandlers.MaxForwardRequestHandler.java
/** * Will write all the headers included in the request to the method. * The difference between this method and setHeaders in BasicRequestHandler * is that the BasicRequestHandler will also add Via, x-forwarded-for, etc. * These "special" headers should not be added when the proxy is target * directly with a Max-Forwards: 0 headers. * @param method The method to write to/* w w w. j ava2 s . co m*/ * @param request The incoming request * @see RequestHandlerBase#setHeaders(HttpMethod, HttpServletRequest) */ @SuppressWarnings("rawtypes") private void setAllHeaders(HttpMethod method, HttpServletRequest request) { Enumeration headers = request.getHeaderNames(); while (headers.hasMoreElements()) { String name = (String) headers.nextElement(); Enumeration value = request.getHeaders(name); while (value.hasMoreElements()) { method.addRequestHeader(name, (String) value.nextElement()); } } }
From source file:com.xpn.xwiki.plugin.feed.XWikiFeedFetcher.java
/** * @see com.sun.syndication.fetcher.FeedFetcher#retrieveFeed(java.net.URL) */// w w w.j av a 2 s . co m public SyndFeed retrieveFeed(URL feedUrl, int timeout) throws IllegalArgumentException, IOException, FeedException, FetcherException { if (feedUrl == null) { throw new IllegalArgumentException("null is not a valid URL"); } HttpClient client = new HttpClient(); if (timeout != 0) { client.getParams().setSoTimeout(timeout); client.getParams().setParameter("http.connection.timeout", new Integer(timeout)); } System.setProperty("http.useragent", getUserAgent()); client.getParams().setParameter("httpclient.useragent", getUserAgent()); String proxyHost = System.getProperty("http.proxyHost"); String proxyPort = System.getProperty("http.proxyPort"); if ((proxyHost != null) && (!proxyHost.equals(""))) { int port = 3128; if ((proxyPort != null) && (!proxyPort.equals(""))) { port = Integer.parseInt(proxyPort); } client.getHostConfiguration().setProxy(proxyHost, port); } String proxyUser = System.getProperty("http.proxyUser"); if ((proxyUser != null) && (!proxyUser.equals(""))) { String proxyPassword = System.getProperty("http.proxyPassword"); Credentials defaultcreds = new UsernamePasswordCredentials(proxyUser, proxyPassword); client.getState().setProxyCredentials(AuthScope.ANY, defaultcreds); } String urlStr = feedUrl.toString(); FeedFetcherCache cache = getFeedInfoCache(); if (cache != null) { // retrieve feed HttpMethod method = new GetMethod(urlStr); method.addRequestHeader("Accept-Encoding", "gzip"); 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()); } } method.setFollowRedirects(true); 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(); } } else { // cache is not in use HttpMethod method = new GetMethod(urlStr); try { method.setFollowRedirects(true); int statusCode = client.executeMethod(method); fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr); handleErrorCodes(statusCode); return getFeed(null, urlStr, method, statusCode); } finally { method.releaseConnection(); } } }
From source file:com.zimbra.cs.dav.client.WebDavClient.java
protected HttpMethod execute(DavRequest req) throws IOException { HttpMethod m = req.getHttpMethod(mBaseUrl); for (Pair<String, String> header : req.getRequestHeaders()) { m.addRequestHeader(header.getFirst(), header.getSecond()); }/* www.j av a 2s .com*/ return executeMethod(m, req.getDepth(), req.getRequestMessageString()); }
From source file:com.sun.syndication.fetcher.impl.HttpClientFeedFetcher.java
/** * @see com.sun.syndication.fetcher.FeedFetcher#retrieveFeed(java.net.URL) *//*from w w w .j av a2s . co m*/ 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:liveplugin.toolwindow.addplugin.git.jetbrains.plugins.github.api.GithubApiUtil.java
@NotNull private static HttpMethod doREST(@NotNull final GithubAuthData auth, @NotNull final String uri, @Nullable final String requestBody, @NotNull final Collection<Header> headers, @NotNull final HttpVerb verb) throws IOException { HttpClient client = getHttpClient(auth.getBasicAuth(), auth.isUseProxy()); return GithubSslSupport.getInstance().executeSelfSignedCertificateAwareRequest(client, uri, new ThrowableConvertor<String, HttpMethod, IOException>() { @Override// w w w. j a va 2 s . c om public HttpMethod convert(String uri) throws IOException { HttpMethod method; switch (verb) { case POST: method = new PostMethod(uri); if (requestBody != null) { ((PostMethod) method).setRequestEntity( new StringRequestEntity(requestBody, "application/json", "UTF-8")); } break; case GET: method = new GetMethod(uri); break; case DELETE: method = new DeleteMethod(uri); break; case HEAD: method = new HeadMethod(uri); break; default: throw new IllegalStateException("Wrong HttpVerb: unknown method: " + verb.toString()); } GithubAuthData.TokenAuth tokenAuth = auth.getTokenAuth(); if (tokenAuth != null) { method.addRequestHeader("Authorization", "token " + tokenAuth.getToken()); } for (Header header : headers) { method.addRequestHeader(header); } return method; } }); }
From source file:com.kodokux.github.api.GithubApiUtil.java
@NotNull private static HttpMethod doREST(@NotNull final GithubAuthData auth, @NotNull final String uri, @Nullable final String requestBody, @NotNull final Collection<Header> headers, @NotNull final HttpVerb verb) throws IOException { HttpClient client = getHttpClient(auth.getBasicAuth(), auth.isUseProxy()); HttpMethod method; switch (verb) { case POST:/*from w w w.ja v a 2 s . c om*/ method = new PostMethod(uri); if (requestBody != null) { ((PostMethod) method) .setRequestEntity(new StringRequestEntity(requestBody, "application/json", "UTF-8")); } break; case GET: method = new GetMethod(uri); break; case DELETE: method = new DeleteMethod(uri); break; case HEAD: method = new HeadMethod(uri); break; default: throw new IllegalStateException("Wrong HttpVerb: unknown method: " + verb.toString()); } GithubAuthData.TokenAuth tokenAuth = auth.getTokenAuth(); if (tokenAuth != null) { method.addRequestHeader("Authorization", "token " + tokenAuth.getToken()); } for (Header header : headers) { method.addRequestHeader(header); } client.executeMethod(method); return method; }
From source file:com.rometools.fetcher.impl.HttpClientFeedFetcher.java
@Override public SyndFeed retrieveFeed(final String userAgent, final URL feedUrl) throws IllegalArgumentException, IOException, FeedException, FetcherException { if (feedUrl == null) { throw new IllegalArgumentException("null is not a valid URL"); }//from www . j av a2 s . com final HttpClient client = new HttpClient(httpClientParams); if (credentialSupplier != null) { final HttpClientParams params = client.getParams(); params.setAuthenticationPreemptive(true); final String host = feedUrl.getHost(); final Credentials credentials = credentialSupplier.getCredentials(null, host); if (credentials != null) { final AuthScope authScope = new AuthScope(host, -1); final HttpState state = client.getState(); state.setCredentials(authScope, credentials); } } System.setProperty("httpclient.useragent", userAgent); final String urlStr = feedUrl.toString(); final HttpMethod method = new GetMethod(urlStr); if (customRequestHeaders == null) { method.addRequestHeader("Accept-Encoding", "gzip"); method.addRequestHeader("User-Agent", userAgent); } else { for (final Map.Entry<String, String> entry : customRequestHeaders.entrySet()) { method.addRequestHeader(entry.getKey(), entry.getValue()); } if (!customRequestHeaders.containsKey("Accept-Encoding")) { method.addRequestHeader("Accept-Encoding", "gzip"); } if (!customRequestHeaders.containsKey("User-Agent")) { method.addRequestHeader("User-Agent", userAgent); } } method.setFollowRedirects(true); if (httpClientMethodCallback != null) { synchronized (httpClientMethodCallback) { httpClientMethodCallback.afterHttpClientMethodCreate(method); } } final FeedFetcherCache cache = getFeedInfoCache(); if (cache != null) { // retrieve feed try { if (isUsingDeltaEncoding()) { method.setRequestHeader("A-IM", "feed"); } // try to get the feed info from the cache SyndFeedInfo syndFeedInfo = cache.getFeedInfo(feedUrl); if (syndFeedInfo != null) { method.setRequestHeader("If-None-Match", syndFeedInfo.getETag()); final Object lastModifiedHeader = syndFeedInfo.getLastModified(); if (lastModifiedHeader instanceof String) { method.setRequestHeader("If-Modified-Since", (String) lastModifiedHeader); } } final 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(feedUrl, syndFeedInfo); // the feed may have been modified to pick up cached values // (eg - for delta encoding) feed = syndFeedInfo.getSyndFeed(); return feed; } finally { method.releaseConnection(); } } else { // cache is not in use try { final int statusCode = client.executeMethod(method); fireEvent(FetcherEvent.EVENT_TYPE_FEED_POLLED, urlStr); handleErrorCodes(statusCode); return getFeed(null, urlStr, method, statusCode); } finally { method.releaseConnection(); } } }
From source file:com.itude.mobile.mobbl.server.http.HttpDelegate.java
private void prepareConnection(HttpMethod method, String userAgent, ArrayList<Cookie> cookies, Header[] requestHeaders, boolean acceptXml, boolean followRedirects) { logger.debug("HttpDelegate.prepareConnection()"); if (logger.isDebugEnabled()) HeaderUtil.printRequestHeaders(logger, method); if (acceptXml) method.addRequestHeader("Accept", "application/xml, */*"); if (cookies != null) { for (Cookie cookie : cookies) method.addRequestHeader("Cookie", cookie.getName() + "=" + cookie.getValue()); }/*from w w w . j a v a 2 s .c o m*/ if (userAgent != null) method.addRequestHeader(Constants.USER_AGENT, userAgent); method.setFollowRedirects(followRedirects); if (requestHeaders != null) for (Header h : requestHeaders) method.addRequestHeader(h); }
From source file:com.foglyn.fogbugz.Request.java
private <T> T request(String url, HttpMethod method, IProgressMonitor monitor, ResponseProcessor<T> processor) throws FogBugzException { Utils.checkCancellation(monitor);/* ww w . jav a 2 s.co m*/ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, repositoryLocation, monitor); if (allowGzip) { method.addRequestHeader("Accept-Encoding", "gzip"); } InputStream responseStream = null; CancellableInputStream cancellableStream = null; try { log.debug("Sending request to server"); int code = WebUtil.execute(httpClient, hostConfiguration, method, monitor); log.debug("Got " + code + " response"); if (!processor.checkHttpStatus(code)) { Map<String, String> headers = Utils.convertHeadersToMap(method); method.abort(); throw unexpectedStatus(code, url, headers); } log.debug("Downloading data"); responseStream = method.getResponseBodyAsStream(); InputStream processed = responseStream; // may be null, for example for HEAD request if (processed != null) { Header contentEncoding = method.getResponseHeader("Content-Encoding"); if (allowGzip && contentEncoding != null && "gzip".equals(contentEncoding.getValue())) { processed = new GZIPInputStream(processed); } cancellableStream = new CancellableInputStream(processed, monitor, threadFactory); processed = cancellableStream; } log.debug("Processing response"); return processor.processResponse(url, method, processed); } catch (RuntimeException e) { // also catches OperationCanceledException // we don't know what happened to method, so we better abort processing method.abort(); log.error("Error while executing request", e); throw e; } catch (IOException e) { // we don't know what happened... better abort connection method.abort(); log.error("IO Error while executing request", e); throw ioError(e, url); } finally { if (cancellableStream != null) { cancellableStream.shutdownBackgroundThread(); } // don't use cancellable stream to close responseStream -- because in case of cancelled monitor, it would ignore close request Utils.close(responseStream); method.releaseConnection(); } }
From source file:net.sf.ehcache.constructs.web.filter.CachingFilterTest.java
/** * When the servlet container generates a 404 page not found, we want to pass * it through without caching and without adding anything to it. * <p/>//from www .j ava 2s . com * Manual Test: wget -d --server-response --header='Accept-Encoding: gzip' http://localhost:9080/non_ok/PageNotFound.jsp */ public void testNotFound() throws Exception { String url = "http://localhost:9080/non_ok/PageNotFound.jsp"; HttpClient httpClient = new HttpClient(); HttpMethod httpMethod = new GetMethod(url); httpMethod.addRequestHeader("If-modified-Since", "Fri, 13 May 3006 23:54:18 GMT"); httpMethod.addRequestHeader("Accept-Encoding", "gzip"); int responseCode = httpClient.executeMethod(httpMethod); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, responseCode); String responseBody = httpMethod.getResponseBodyAsString(); assertNotNull(responseBody); assertNull(httpMethod.getResponseHeader("Content-Encoding")); }