Example usage for org.apache.commons.httpclient HttpMethod addRequestHeader

List of usage examples for org.apache.commons.httpclient HttpMethod addRequestHeader

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod addRequestHeader.

Prototype

public abstract void addRequestHeader(String paramString1, String paramString2);

Source Link

Usage

From source file:net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilterTest.java

/**
 * A 0 length body should give a 0 length nongzipped body and content length
 * Manual Test: wget -d --server-response --timestamping --header='If-modified-Since: Fri, 13 May 3006 23:54:18 GMT' --header='Accept-Encoding: gzip' http://localhost:9090/empty_caching_filter/empty.html
 *//*from   w w w.j  a v  a  2  s . com*/
@Test
public void testIfModifiedZeroLengthHTML() throws Exception {

    String url = buildUrl("/empty_caching_filter/empty.html");
    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);
    assertTrue(
            HttpURLConnection.HTTP_OK == responseCode || HttpURLConnection.HTTP_NOT_MODIFIED == responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertTrue("".equals(responseBody) || null == responseBody);
    checkNullOrZeroContentLength(httpMethod);
}

From source file:net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilterTest.java

/**
 * Servlets and JSPs can send content even when the response is set to no content.
 * In this case there should not be a body but there is. Orion seems to kill the body
 * after is has left the Servlet filter chain. To avoid wget going into an inifinite
 * retry loop, and presumably some other web clients, the content length should be 0
 * and the body 0.//w w w  .  jav  a2s. c om
 * <p/>
 * wget -d --server-response --timestamping --header='If-modified-Since: Fri, 13 May 3006 23:54:18 GMT' --header='Accept-Encoding: gzip' http://localhost:9090/empty_caching_filter/SC_NOT_MODIFIED.jsp
 */
@Test
public void testNotModifiedJSPGzipFilter() throws Exception {

    String url = buildUrl("/empty_caching_filter/SC_NOT_MODIFIED.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_MODIFIED, responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertEquals(null, responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));
    assertNotNull(httpMethod.getResponseHeader("Last-Modified").getValue());
    checkNullOrZeroContentLength(httpMethod);

}

From source file:net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilterTest.java

/**
 * Servlets and JSPs can send content even when the response is set to no content.
 * In this case there should not be a body but there is. Orion seems to kill the body
 * after is has left the Servlet filter chain. To avoid wget going into an inifinite
 * retry loop, and presumably some other web clients, the content length should be 0
 * and the body 0.//from  www. j a v  a  2  s  .  co  m
 * <p/>
 * Manual Test: wget -d --server-response --timestamping --header='If-modified-Since: Fri, 13 May 3006 23:54:18 GMT' --header='Accept-Encoding: gzip' http://localhost:9090/empty_caching_filter/SC_NO_CONTENT.jsp
 */
@Test
public void testNoContentJSPGzipFilter() throws Exception {

    String url = buildUrl("/empty_caching_filter/SC_NO_CONTENT.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_NO_CONTENT, responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertEquals(null, responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));
    assertNotNull(httpMethod.getResponseHeader("Last-Modified").getValue());
    checkNullOrZeroContentLength(httpMethod);

}

From source file:com.zimbra.cs.account.auth.HostedAuth.java

/**
 * zmprov md test.com zimbraAuthMech 'custom:hosted http://auth.customer.com:80'
 * //  ww  w . j  a  v a 2s . c o m
 *  This custom auth module takes arguments in the following form:
 * {URL} [GET|POST - default is GET] [encryption method - defautl is plain] [auth protocol - default is imap] 
 * e.g.: http://auth.customer.com:80 GET
 **/
public void authenticate(Account acct, String password, Map<String, Object> context, List<String> args)
        throws Exception {
    HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
    HttpMethod method = null;

    String targetURL = args.get(0);
    /*
    if (args.size()>2) {
       authMethod = args.get(2);
    }
            
    if (args.size()>3) {
       authMethod = args.get(3);
    }*/

    if (args.size() > 1) {
        if (args.get(1).equalsIgnoreCase("GET"))
            method = new GetMethod(targetURL);
        else
            method = new PostMethod(targetURL);
    } else
        method = new GetMethod(targetURL);

    if (context.get(AuthContext.AC_ORIGINATING_CLIENT_IP) != null)
        method.addRequestHeader(HEADER_CLIENT_IP, context.get(AuthContext.AC_ORIGINATING_CLIENT_IP).toString());

    if (context.get(AuthContext.AC_REMOTE_IP) != null)
        method.addRequestHeader(HEADER_X_ZIMBRA_REMOTE_ADDR, context.get(AuthContext.AC_REMOTE_IP).toString());

    method.addRequestHeader(HEADER_AUTH_USER, acct.getName());
    method.addRequestHeader(HEADER_AUTH_PASSWORD, password);

    AuthContext.Protocol proto = (AuthContext.Protocol) context.get(AuthContext.AC_PROTOCOL);
    if (proto != null)
        method.addRequestHeader(HEADER_AUTH_PROTOCOL, proto.toString());

    if (context.get(AuthContext.AC_USER_AGENT) != null)
        method.addRequestHeader(HEADER_AUTH_USER_AGENT, context.get(AuthContext.AC_USER_AGENT).toString());

    try {
        HttpClientUtil.executeMethod(client, method);
    } catch (HttpException ex) {
        throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), acct.getName(),
                "HTTP request to remote authentication server failed", ex);
    } catch (IOException ex) {
        throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), acct.getName(),
                "HTTP request to remote authentication server failed", ex);
    } finally {
        if (method != null)
            method.releaseConnection();
    }

    int status = method.getStatusCode();
    if (status != HttpStatus.SC_OK) {
        throw AuthFailedServiceException.AUTH_FAILED(acct.getName(),
                "HTTP request to remote authentication server failed. Remote response code: "
                        + Integer.toString(status));
    }

    String responseMessage;
    if (method.getResponseHeader(HEADER_AUTH_STATUS) != null) {
        responseMessage = method.getResponseHeader(HEADER_AUTH_STATUS).getValue();
    } else {
        throw AuthFailedServiceException.AUTH_FAILED(acct.getName(),
                "Empty response from remote authentication server.");
    }
    if (responseMessage.equalsIgnoreCase(AUTH_STATUS_OK)) {
        return;
    } else {
        throw AuthFailedServiceException.AUTH_FAILED(acct.getName(), responseMessage);
    }

}

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.
 *///from  w  w  w .j  a v  a2  s.c  o m
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:freeciv.servlet.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
 * @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
 *//*from   ww  w .  j  a v  a2  s .com*/
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    httpMethodProxyRequest.setFollowRedirects(false);
    String port = "" + httpServletRequest.getSession().getAttribute("civserverport");
    String host = "" + httpServletRequest.getSession().getAttribute("civserverhost");
    String username = "" + httpServletRequest.getSession().getAttribute("username");
    httpMethodProxyRequest.addRequestHeader("civserverport", port);
    httpMethodProxyRequest.addRequestHeader("civserverhost", host);
    httpMethodProxyRequest.addRequestHeader("username", username);
    int intProxyResponseCode = 0;
    // Execute the request
    try {
        intProxyResponseCode = client.executeMethod(httpMethodProxyRequest);
    } catch (IOException ioErr) {
        //- If an I/O (transport) error occurs. Some transport exceptions can be recovered from. 
        //- If a protocol exception occurs. Usually protocol exceptions cannot be recovered from.
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        httpServletResponse.setStatus(502);
        outputStreamClientResponse
                .write("Freeciv web client proxy not responding (most likely died).".getBytes());
        httpMethodProxyRequest.releaseConnection();
        return;
    }

    // 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) {
            httpMethodProxyRequest.releaseConnection();
            throw new ServletException("Recieved 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();
        httpServletResponse.sendRedirect(
                stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
        httpMethodProxyRequest.releaseConnection();
        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);
        httpMethodProxyRequest.releaseConnection();
        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) {
        httpServletResponse.setHeader(header.getName(), header.getValue());
    }

    // Send the content to the client
    InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
    OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
    int intNextByte;
    while ((intNextByte = bufferedInputStream.read()) != -1) {
        outputStreamClientResponse.write(intNextByte);
    }
    httpMethodProxyRequest.releaseConnection();
}

From source file:com.boyuanitsm.pay.alipay.util.httpClient.HttpProtocolHandler.java

/**
 * Http//from w  w  w  .  ja  v  a2  s .  c o  m
 * 
 * @param request ?
 * @param strParaFileName ???
 * @param strFilePath 
 * @return 
 * @throws HttpException, IOException 
 */
public HttpResponse execute(HttpRequest request, String strParaFileName, String strFilePath)
        throws HttpException, IOException {
    HttpClient httpclient = new HttpClient(connectionManager);

    // 
    int connectionTimeout = defaultConnectionTimeout;
    if (request.getConnectionTimeout() > 0) {
        connectionTimeout = request.getConnectionTimeout();
    }
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

    // 
    int soTimeout = defaultSoTimeout;
    if (request.getTimeout() > 0) {
        soTimeout = request.getTimeout();
    }
    httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);

    // ConnectionManagerconnection
    httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);

    String charset = request.getCharset();
    charset = charset == null ? DEFAULT_CHARSET : charset;
    HttpMethod method = null;

    //get??
    if (request.getMethod().equals(HttpRequest.METHOD_GET)) {
        method = new GetMethod(request.getUrl());
        method.getParams().setCredentialCharset(charset);

        // parseNotifyConfig??GETrequestQueryString
        method.setQueryString(request.getQueryString());
    } else if (strParaFileName.equals("") && strFilePath.equals("")) {
        //post??
        method = new PostMethod(request.getUrl());
        ((PostMethod) method).addParameters(request.getParameters());
        method.addRequestHeader("Content-Type",
                "application/x-www-form-urlencoded; text/html; charset=" + charset);
    } else {
        //post?
        method = new PostMethod(request.getUrl());
        List<Part> parts = new ArrayList<Part>();
        for (int i = 0; i < request.getParameters().length; i++) {
            parts.add(new StringPart(request.getParameters()[i].getName(),
                    request.getParameters()[i].getValue(), charset));
        }
        //?strParaFileName???
        parts.add(new FilePart(strParaFileName, new FilePartSource(new File(strFilePath))));

        // 
        ((PostMethod) method).setRequestEntity(
                new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams()));
    }

    // Http HeaderUser-Agent
    method.addRequestHeader("User-Agent", "Mozilla/4.0");
    HttpResponse response = new HttpResponse();

    try {
        httpclient.executeMethod(method);
        if (request.getResultType().equals(HttpResultType.STRING)) {
            response.setStringResult(method.getResponseBodyAsString());
        } else if (request.getResultType().equals(HttpResultType.BYTES)) {
            response.setByteResult(method.getResponseBody());
        }
        response.setResponseHeaders(method.getResponseHeaders());
    } catch (UnknownHostException ex) {

        return null;
    } catch (IOException ex) {

        return null;
    } catch (Exception ex) {

        return null;
    } finally {
        method.releaseConnection();
    }
    return response;
}

From source file:com.zimbra.cs.servlet.ZimbraServlet.java

public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod method,
        HttpState state) throws IOException, ServiceException {
    // create an HTTP client with the same cookies
    javax.servlet.http.Cookie cookies[] = req.getCookies();
    String hostname = method.getURI().getHost();
    boolean hasZMAuth = hasZimbraAuthCookie(state);
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(ZimbraCookie.COOKIE_ZM_AUTH_TOKEN) && hasZMAuth)
                continue;
            state.addCookie(//from w  w w  . j ava 2 s .c o m
                    new Cookie(hostname, cookies[i].getName(), cookies[i].getValue(), "/", null, false));
        }
    }
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    if (state != null)
        client.setState(state);

    int hopcount = 0;
    for (Enumeration<?> enm = req.getHeaderNames(); enm.hasMoreElements();) {
        String hname = (String) enm.nextElement(), hlc = hname.toLowerCase();
        if (hlc.equals("x-zimbra-hopcount"))
            try {
                hopcount = Math.max(Integer.parseInt(req.getHeader(hname)), 0);
            } catch (NumberFormatException e) {
            }
        else if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.equals("authorization"))
            method.addRequestHeader(hname, req.getHeader(hname));
    }
    if (hopcount >= MAX_PROXY_HOPCOUNT)
        throw ServiceException.TOO_MANY_HOPS(HttpUtil.getFullRequestURL(req));
    method.addRequestHeader("X-Zimbra-Hopcount", Integer.toString(hopcount + 1));
    if (method.getRequestHeader("X-Zimbra-Orig-Url") == null)
        method.addRequestHeader("X-Zimbra-Orig-Url", req.getRequestURL().toString());
    String ua = req.getHeader("User-Agent");
    if (ua != null)
        method.setRequestHeader("User-Agent", ua);

    // dispatch the request and copy over the results
    int statusCode = -1;
    for (int retryCount = 3; statusCode == -1 && retryCount > 0; retryCount--) {
        statusCode = HttpClientUtil.executeMethod(client, method);
    }
    if (statusCode == -1) {
        resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "retry limit reached");
        return;
    } else if (statusCode >= 300) {
        resp.sendError(statusCode, method.getStatusText());
        return;
    }

    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        String hname = headers[i].getName(), hlc = hname.toLowerCase();
        if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.startsWith("www-"))
            resp.addHeader(hname, headers[i].getValue());
    }
    InputStream responseStream = method.getResponseBodyAsStream();
    if (responseStream == null || resp.getOutputStream() == null)
        return;
    ByteUtil.copy(method.getResponseBodyAsStream(), false, resp.getOutputStream(), false);
}

From source file:com.datos.vfs.provider.webdav.WebdavFileObject.java

/**
 * Prepares a Method object./*  w ww . j  a v a 2  s  .  c  om*/
 *
 * @param method the HttpMethod.
 * @throws FileSystemException if an error occurs encoding the uri.
 * @throws URIException        if the URI is in error.
 */
@Override
protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException {
    final String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(this.getUrlCharset());
    method.setPath(pathEncoded);
    method.setFollowRedirects(this.getFollowRedirect());
    method.setRequestHeader("User-Agent", "Jakarta-Commons-VFS");
    method.addRequestHeader("Cache-control", "no-cache");
    method.addRequestHeader("Cache-store", "no-store");
    method.addRequestHeader("Pragma", "no-cache");
    method.addRequestHeader("Expires", "0");
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

public static void addBasicAuthHeaderForUser(HttpMethod method, Account acct, String password)
        throws UnsupportedEncodingException {
    String basicAuthEncoding = DatatypeConverter
            .printBase64Binary(String.format("%s:%s", acct.getName(), password).getBytes("UTF-8"));
    method.addRequestHeader("Authorization", "Basic " + basicAuthEncoding);
}