Example usage for org.apache.http.client.methods HttpUriRequest setHeader

List of usage examples for org.apache.http.client.methods HttpUriRequest setHeader

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest setHeader.

Prototype

void setHeader(String str, String str2);

Source Link

Usage

From source file:org.wso2.carbon.automation.extensions.servers.httpserver.SimpleHttpClient.java

private void setHeaders(Map<String, String> headers, HttpUriRequest request) {
    if (headers != null && headers.size() > 0) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            request.setHeader(header.getKey(), header.getValue());
        }//from w  w w.jav  a 2s  .  c o  m
    }
}

From source file:org.idansof.otp.client.Planner.java

public PlanResult generatePlan(PlanRequest planRequest)
        throws IOException, XmlPullParserException, ParseException {

    AndroidHttpClient androidHttpClient = AndroidHttpClient.newInstance("");
    try {/*from  www  .  j  a  v  a  2  s. c om*/

        DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, locale);

        Uri.Builder builder = Uri.parse("http://" + host).buildUpon();

        builder.appendEncodedPath(uri);
        builder.appendQueryParameter("fromPlace", planRequest.getFrom().getCoordinateString());
        builder.appendQueryParameter("toPlace", planRequest.getTo().getCoordinateString());
        builder.appendQueryParameter("date", dateFormat.format(planRequest.getDate()));
        builder.appendQueryParameter("time", timeFormat.format(planRequest.getDate()));

        HttpProtocolParams.setContentCharset(androidHttpClient.getParams(), "utf-8");
        String uri = builder.build().toString();
        Log.i(Planner.class.toString(), "Fetching plan from " + uri);
        HttpUriRequest httpUriRequest = new HttpGet(uri);
        httpUriRequest.setHeader("Accept", "text/xml");
        HttpResponse httpResponse = androidHttpClient.execute(httpUriRequest);

        InputStream contentStream = httpResponse.getEntity().getContent();
        Log.i(Planner.class.toString(),
                "Parsing content , size :" + httpResponse.getEntity().getContentLength());
        return parseXMLResponse(contentStream);
    } finally {
        androidHttpClient.close();
    }
}

From source file:com.prestomation.android.sospy.monitor.AppEngineClient.java

private HttpResponse makeRequestNoRetry(HttpUriRequest request, List<NameValuePair> params) throws Exception {
    // Get auth token for account
    String ascidCookie = getASCIDCookie(true);

    // Make POST request
    DefaultHttpClient client = new DefaultHttpClient();

    request.setHeader("Cookie", ascidCookie);
    request.setHeader("X-Same-Domain", "1"); // XSRF
    HttpResponse res = client.execute(request);
    return res;/*from w  w w.  ja  v  a 2s. c  o m*/
}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.rest.RequestHandlerImpl.java

private void setHeaders(HttpUriRequest httpUriRequest, Request request) {
    if (request.getHeaderFields() == null || request.getHeaderFields().isEmpty()) {
        return;/*from ww  w  .  jav  a2 s . c  om*/
    }
    for (String fieldName : request.getHeaderFields().keySet()) {
        String fieldValue = request.getHeaderFields().get(fieldName);
        httpUriRequest.setHeader(fieldName, fieldValue);
    }
}

From source file:me.xiaopan.sketch.http.HttpClientStack.java

@Override
public ImageHttpResponse getHttpResponse(String uri) throws IOException {
    HttpUriRequest httpUriRequest = new HttpGet(uri);

    if (userAgent != null) {
        httpUriRequest.setHeader("User-Agent", userAgent);
    }/* w  w  w .ja  v a  2s. co m*/

    if (addExtraHeaders != null && addExtraHeaders.size() > 0) {
        for (Map.Entry<String, String> entry : addExtraHeaders.entrySet()) {
            httpUriRequest.addHeader(entry.getKey(), entry.getValue());
        }
    }
    if (setExtraHeaders != null && setExtraHeaders.size() > 0) {
        for (Map.Entry<String, String> entry : setExtraHeaders.entrySet()) {
            httpUriRequest.setHeader(entry.getKey(), entry.getValue());
        }
    }

    processRequest(uri, httpUriRequest);

    HttpResponse httpResponse = httpClient.execute(httpUriRequest);
    return new HttpClientHttpResponse(httpResponse);
}

From source file:org.quizpoll.net.AppEngineHelper.java

/**
 * Adds AppEngine cookies to the request
 *//*from  w ww  . j a  v a  2  s.c  o m*/
private HttpUriRequest addCookie(HttpUriRequest request) {
    String cookie = Preferences.getString(PrefType.COOKIE_APPENGINE, activity);
    if (cookie != null) {
        request.setHeader("Cookie", cookie);
    }
    return request;
}

From source file:org.pixmob.feedme.net.NetworkClient.java

private void prepareRequest(HttpUriRequest req) throws NetworkClientException {
    final String authToken = getAuthToken();
    if (authToken == null) {
        throw new NetworkClientException("Missing authentication token", req.getURI().toString());
    }/*from  w ww  .j a va  2  s.  co  m*/
    req.setHeader("Authorization", "GoogleLogin auth=" + authToken);
}

From source file:com.testlinkrestapi.restclient.RestClient.java

private HttpUriRequest auth(HttpUriRequest request, String username, String password) {
    String encoding;/* w w  w  .  j a v  a 2s .  co  m*/
    try {
        encoding = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"));
        request.setHeader("Authorization", "Basic " + encoding);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return request;
}

From source file:org.ops4j.pax.url.mvn.internal.wagon.ConfigurableHttpWagon.java

@Override
protected CloseableHttpResponse execute(HttpUriRequest httpMethod) throws HttpException, IOException {
    setHeaders(httpMethod);//from   www. j  a v a2 s  . com
    String userAgent = getUserAgent(httpMethod);
    if (userAgent != null) {
        httpMethod.setHeader(HTTP.USER_AGENT, userAgent);
    }

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    // WAGON-273: default the cookie-policy to browser compatible
    requestConfigBuilder.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY);

    Repository repo = getRepository();
    ProxyInfo proxyInfo = getProxyInfo(repo.getProtocol(), repo.getHost());
    if (proxyInfo != null) {
        HttpHost proxy = new HttpHost(proxyInfo.getHost(), proxyInfo.getPort());
        requestConfigBuilder.setProxy(proxy);
    }

    HttpMethodConfiguration config = getHttpConfiguration() == null ? null
            : getHttpConfiguration().getMethodConfiguration(httpMethod);

    if (config != null) {
        copyConfig(config, requestConfigBuilder);
    } else {
        requestConfigBuilder.setSocketTimeout(getReadTimeout());
        requestConfigBuilder.setConnectTimeout(getTimeout());
    }

    getLocalContext().setRequestConfig(requestConfigBuilder.build());

    if (config != null && config.isUsePreemptive()) {
        HttpHost targetHost = new HttpHost(repo.getHost(), repo.getPort(), repo.getProtocol());
        AuthScope targetScope = getBasicAuthScope().getScope(targetHost);

        if (getCredentialsProvider().getCredentials(targetScope) != null) {
            BasicScheme targetAuth = new BasicScheme();
            targetAuth.processChallenge(new BasicHeader(AUTH.WWW_AUTH, "BASIC preemptive"));
            getAuthCache().put(targetHost, targetAuth);
        }
    }

    if (proxyInfo != null) {
        if (proxyInfo.getHost() != null) {
            HttpHost proxyHost = new HttpHost(proxyInfo.getHost(), proxyInfo.getPort());
            AuthScope proxyScope = getProxyBasicAuthScope().getScope(proxyHost);

            String proxyUsername = proxyInfo.getUserName();
            String proxyPassword = proxyInfo.getPassword();
            String proxyNtlmHost = proxyInfo.getNtlmHost();
            String proxyNtlmDomain = proxyInfo.getNtlmDomain();

            if (proxyUsername != null && proxyPassword != null) {
                Credentials creds;
                if (proxyNtlmHost != null || proxyNtlmDomain != null) {
                    creds = new NTCredentials(proxyUsername, proxyPassword, proxyNtlmHost, proxyNtlmDomain);
                } else {
                    creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
                }

                getCredentialsProvider().setCredentials(proxyScope, creds);
                BasicScheme proxyAuth = new BasicScheme();
                proxyAuth.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC preemptive"));
                getAuthCache().put(proxyHost, proxyAuth);
            }
        }
    }

    return client.execute(httpMethod, getLocalContext());
}

From source file:com.linecorp.armeria.server.http.HttpServiceTest.java

@Test
public void testContentLength() throws Exception {
    // Test if the server responds with the 'content-length' header
    // even if it is the last response of the connection.
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        HttpUriRequest req = new HttpGet(newUri("/200"));
        req.setHeader("Connection", "Close");
        try (CloseableHttpResponse res = hc.execute(req)) {
            assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
            assertThat(res.containsHeader("Content-Length"), is(true));
            assertThat(res.getHeaders("Content-Length").length, is(1));
            assertThat(res.getHeaders("Content-Length")[0].getValue(), is("6"));
            assertThat(EntityUtils.toString(res.getEntity()), is("200 OK"));
        }/*from  w  w w.  ja v  a2 s.  c om*/
    }

    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        // Ensure the HEAD response does not have content.
        try (CloseableHttpResponse res = hc.execute(new HttpHead(newUri("/200")))) {
            assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
            assertThat(res.getEntity(), is(nullValue()));
        }

        // Ensure the 204 response does not have content.
        try (CloseableHttpResponse res = hc.execute(new HttpGet(newUri("/204")))) {
            assertThat(res.getStatusLine().toString(), is("HTTP/1.1 204 No Content"));
            assertThat(res.getEntity(), is(nullValue()));
        }
    }
}