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:com.zimbra.cs.util.WebClientServiceUtil.java

/**
 * send service request to every ui node
 * @param serviceUrl the url that should be matched and handled by ServiceServlet in ZimbraWebClient
 * @throws ServiceException/*from  w  w  w  .ja  v  a 2s  . c  o m*/
 */
public static void sendServiceRequestToEveryUiNode(String serviceUrl) throws ServiceException {
    List<Server> servers = Provisioning.getInstance().getAllServers(Provisioning.SERVICE_WEBCLIENT);
    if (servers == null || servers.isEmpty()) {
        servers.add(Provisioning.getInstance().getLocalServer());
    }
    AuthToken authToken = AuthProvider.getAdminAuthToken();
    ZimbraLog.misc.debug("got admin auth token");
    //sequentially flush each node
    HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
    HttpProxyUtil.configureProxy(client);
    for (Server server : servers) {
        if (isServerAtLeast8dot5(server)) {
            HttpMethod method = null;
            try {
                method = new GetMethod(URLUtil.getServiceURL(server, serviceUrl, false));
                ZimbraLog.misc.debug("connecting to ui node %s", server.getName());
                try {
                    method.addRequestHeader(PARAM_AUTHTOKEN, authToken.getEncoded());
                } catch (AuthTokenException e) {
                    ZimbraLog.misc.warn(e);
                }
                int respCode = HttpClientUtil.executeMethod(client, method);
                if (respCode != 200) {
                    ZimbraLog.misc.warn("service failed, return code: %d", respCode);
                }
            } catch (Exception e) {
                ZimbraLog.misc.warn("service failed for node %s", server.getName(), e);
            } finally {
                if (method != null) {
                    method.releaseConnection();
                }
            }
        }
    }
    if (authToken != null && authToken.isRegistered()) {
        try {
            authToken.deRegister();
            ZimbraLog.misc.debug("de-registered auth token, isRegistered?%s", authToken.isRegistered());
        } catch (AuthTokenException e) {
            ZimbraLog.misc.warn("failed to de-register auth token", e);
        }
    }
}

From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java

private static void addHeaders(Map<String, String> additionalHeaders, final HttpMethod method) {
    for (String header : additionalHeaders.keySet()) {
        System.err.println("Adding header. " + header + ": " + additionalHeaders.get(header));
        method.addRequestHeader(header, additionalHeaders.get(header));
    }//w w  w  .ja v a2 s .  c o m
}

From source file:CertStreamCallback.java

private static void invokeActions(String url, String params, byte[] data, Part[] parts, String accept,
        String contentType, String sessionID, String language, String method, Callback callback) {

    if (params != null && !"".equals(params)) {
        if (url.contains("?")) {
            url = url + "&" + params;
        } else {// w  ww .  ja v a2s  .c o  m
            url = url + "?" + params;
        }
    }

    if (language != null && !"".equals(language)) {
        if (url.contains("?")) {
            url = url + "&language=" + language;
        } else {
            url = url + "?language=" + language;
        }
    }

    HttpMethod httpMethod = null;

    try {
        HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        httpMethod = getHttpMethod(url, method);
        if ((httpMethod instanceof PostMethod) || (httpMethod instanceof PutMethod)) {
            if (null != data)
                ((EntityEnclosingMethod) httpMethod).setRequestEntity(new ByteArrayRequestEntity(data));
            if (httpMethod instanceof PostMethod && null != parts)
                ((PostMethod) httpMethod)
                        .setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams()));
        }

        if (sessionID != null) {
            httpMethod.addRequestHeader("Cookie", "JSESSIONID=" + sessionID);
        }

        if (!(httpMethod instanceof PostMethod && null != parts)) {
            if (null != accept && !"".equals(accept))
                httpMethod.addRequestHeader("Accept", accept);
            if (null != contentType && !"".equals(contentType))
                httpMethod.addRequestHeader("Content-Type", contentType);
        }

        int statusCode = httpClient.executeMethod(httpMethod);
        if (statusCode != HttpStatus.SC_OK) {
            throw ActionException.create(ClientMessages.CON_ERROR1, httpMethod.getStatusLine());
        }

        contentType = null != httpMethod.getResponseHeader("Content-Type")
                ? httpMethod.getResponseHeader("Content-Type").getValue()
                : accept;

        InputStream o = httpMethod.getResponseBodyAsStream();
        if (callback != null) {
            callback.execute(o, contentType, sessionID);
        }

    } catch (Exception e) {
        String result = BizClientUtils.doError(e, contentType);
        ByteArrayInputStream in = null;
        try {
            in = new ByteArrayInputStream(result.getBytes("UTF-8"));
            if (callback != null) {
                callback.execute(in, contentType, null);
            }

        } catch (UnsupportedEncodingException e1) {
            throw new RuntimeException(e1.getMessage() + "", e1);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    } finally {
        // 
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:eu.eco2clouds.accounting.bonfire.BFClientAccountingImpl.java

private void setHeaders(HttpMethod method) {
    method.addRequestHeader(Dictionary.X_BONFIRE_ASSERTED_ID, userId);
    method.addRequestHeader(Dictionary.X_BONFIRE_GROUPS_ID, groupId);
    method.addRequestHeader("User-Agent", Dictionary.USER_AGENT);
    method.addRequestHeader("Accept", Dictionary.ACCEPT);
}

From source file:net.adamcin.httpsig.http.apache3.Http3UtilTest.java

@Test
public void testAllHeaders() {
    TestBody.test(new HttpServerTestBody() {
        @Override/*ww  w .  j  a v a2 s .co  m*/
        protected void execute() throws Exception {
            List<String> headers = Arrays.asList(Constants.HEADER_REQUEST_TARGET, Constants.HEADER_DATE,
                    "x-test");

            setServlet(new AdminServlet(headers));

            KeyPair keyPair = KeyTestUtil.getKeyPairFromProperties("b2048", "id_rsa");

            DefaultKeychain provider = new DefaultKeychain();
            provider.add(new SSHKey(KeyFormat.SSH_RSA, keyPair));

            HttpClient client = new HttpClient();

            Http3Util.enableAuth(client, provider, getKeyId());
            HttpMethod request = new GetMethod(getAbsoluteUrl(TEST_URL));
            request.addRequestHeader("x-test", "foo");
            try {
                int status = client.executeMethod(request);
                assertEquals("should return 200", 200, status);
            } finally {
                request.releaseConnection();
            }
        }
    });
}

From source file:com.utest.webservice.client.rest.RestClient.java

private HttpMethod setHeader(HttpMethod method) {
    method.addRequestHeader("Accept", accept);
    return method;
}

From source file:colt.nicity.performance.latent.http.ApacheHttpClient.java

private void applyHeadersCommonToAllRequests(HttpMethod method) {
    for (Map.Entry<String, String> headerEntry : headersForEveryRequest.entrySet()) {
        method.addRequestHeader(headerEntry.getKey(), headerEntry.getValue());
    }/*  w  w w.  ja  v a2  s . c om*/
}

From source file:com.tasktop.c2c.server.profile.tests.service.ProfileWebServiceClientTest.java

@Test
public void serviceAcceptsNonCompliantJSONMediaTypes() throws HttpException, IOException {
    String baseUrl = profileWebServiceClient.getBaseUrl();
    for (String mediaType : new String[] { "application/json", "application/x-javascript", "text/javascript",
            "text/x-javascript", "text/x-json", "text/json" }) {
        HttpClient client = new HttpClient();
        HttpMethod get = new GetMethod(baseUrl + "/"
                + ProfileWebServiceClient.GET_PROJECT_BY_IDENTIFIER_URL.replaceAll("\\{.*?\\}", "123"));
        get.addRequestHeader("Accept", mediaType);
        int rc = client.executeMethod(get);
        String responseBody = get.getResponseBodyAsString();

        assertTrue("Expected JSON response for media type \"" + mediaType + "\" but got " + responseBody,
                responseBody.trim().startsWith("{\"error\":{\"message\":"));
    }//w ww . j  ava2 s  .c o  m
}

From source file:net.sf.ehcache.constructs.web.filter.GzipFilterTest.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 w ww .jav  a2s  .c om*/
* Manual Test: wget -d --server-response --header='Accept-Encoding: gzip'  http://localhost:9080/non_ok/PageNotFoundGzip.jsp
*/
public void testNotFound() throws Exception {

    String url = "http://localhost:9080/non_ok/PageNotFoundGzip.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"));
}

From source file:net.sf.ehcache.constructs.web.filter.GzipFilterTest.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/>//  w w w  . j av  a  2  s .  c  om
 * Manual Test: wget -d --server-response --header='Accept-Encoding: gzip'  http://localhost:9080/non_ok/SendRedirectGzip.jsp
 */
public void testRedirect() throws Exception {

    String url = "http://localhost:9080/non_ok/SendRedirectGzip.jsp";
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(url);
    httpMethod.addRequestHeader("Accept-Encoding", "gzip");
    int responseCode = httpClient.executeMethod(httpMethod);
    //httpclient follows redirects, so gets the home page.
    assertEquals(HttpURLConnection.HTTP_OK, responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertNotNull(responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));
}