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

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

Introduction

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

Prototype

void addHeader(String str, String str2);

Source Link

Usage

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 . j a va 2s.  c  o 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:com.petalmd.armor.HeaderAwareJestHttpClient.java

@Override
//    <T extends JestResult> void executeAsync(Action<T> var1, JestResultHandler<? super T> var2);
public <T extends JestResult> void executeAsync(final Action<T> clientRequest,
        final JestResultHandler<? super T> resultHandler) {

    synchronized (this) {
        if (!asyncClient.isRunning()) {
            asyncClient.start();/*from   w ww .ja va 2 s .c  o m*/
        }
    }

    final String elasticSearchRestUrl = getRequestURL(getNextServer(), clientRequest.getURI());

    try {
        final HttpUriRequest request = constructHttpMethod(clientRequest.getRestMethodName(),
                elasticSearchRestUrl, clientRequest.getData(gson));

        // add headers added to action
        if (!clientRequest.getHeaders().isEmpty()) {
            for (final Entry<String, Object> header : clientRequest.getHeaders().entrySet()) {
                request.addHeader(header.getKey(), header.getValue() + "");
            }
        }

        asyncClient.execute(request, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(final HttpResponse response) {
                try {
                    final T jestResult = deserializeResponse(response, clientRequest);
                    resultHandler.completed(jestResult);
                } catch (final IOException e) {
                    log.error(
                            "Exception occurred while serializing the response. Exception: " + e.getMessage());
                }
            }

            @Override
            public void failed(final Exception ex) {
                resultHandler.failed(ex);
            }

            @Override
            public void cancelled() {
            }
        });
    } catch (Exception e) {
    }
}

From source file:eu.nullbyte.android.urllib.Urllib.java

public InputStream openStream(String url, HttpEntity postData, boolean forcePost)
        throws ClientProtocolException, IOException {
    this.currentURI = url;
    String[] headerKeys = (String[]) this.headers.keySet().toArray(new String[headers.size()]);
    String[] headerVals = (String[]) this.headers.values().toArray(new String[headers.size()]);
    HttpUriRequest request;
    if (!forcePost && postData == null) {
        request = new HttpGet(url);
    } else {/*from  w w  w.j a  v  a 2 s. c  o  m*/
        request = new HttpPost(url);
        ((HttpPost) request).setEntity(postData);
    }
    if (userAgent != null) {
        request.addHeader("User-Agent", userAgent);
    }

    for (int i = 0; i < headerKeys.length; i++) {
        request.addHeader(headerKeys[i], headerVals[i]);
    }
    this.currentURI = request.getURI().toString();
    HttpResponse response = httpclient.execute(request);
    HttpEntity entity = response.getEntity();
    return entity.getContent();
}

From source file:ch.cyberduck.core.s3.RequestEntityRestStorageService.java

@Override
protected HttpUriRequest setupConnection(final HTTP_METHOD method, final String bucketName,
        final String objectKey, final Map<String, String> requestParameters) throws S3ServiceException {
    final HttpUriRequest request = super.setupConnection(method, bucketName, objectKey, requestParameters);
    if (preferences.getBoolean("s3.upload.expect-continue")) {
        if ("PUT".equals(request.getMethod())) {
            // #7621
            final Jets3tProperties properties = getJetS3tProperties();
            if (!properties.getBoolProperty("s3service.disable-expect-continue", false)) {
                request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
            }/*from w  w  w. j av  a2 s  . co  m*/
        }
    }
    if (preferences.getBoolean("s3.bucket.requesterpays")) {
        // Only for AWS
        if (session.getHost().getHostname().endsWith(preferences.getProperty("s3.hostname.default"))) {
            // Downloading Objects in Requester Pays Buckets
            if ("GET".equals(request.getMethod()) || "POST".equals(request.getMethod())) {
                final Jets3tProperties properties = getJetS3tProperties();
                if (!properties.getBoolProperty("s3service.disable-request-payer", false)) {
                    // For GET and POST requests, include x-amz-request-payer : requester in the header
                    request.addHeader("x-amz-request-payer", "requester");
                }
            }
        }
    }
    return request;
}

From source file:com.csipsimple.service.DownloadLibService.java

private RemoteLibInfo getLibUpdate(URI updateServerUri, String for_what) {
    HttpClient updateHttpClient = new DefaultHttpClient();

    HttpUriRequest updateReq = new HttpGet(updateServerUri);
    updateReq.addHeader("Cache-Control", "no-cache");

    Log.d(THIS_FILE, "Get updates from " + updateServerUri.toString());

    try {//from   ww  w.j a v  a  2s  . co  m
        HttpResponse updateResponse;
        HttpEntity updateResponseEntity = null;

        updateResponse = updateHttpClient.execute(updateReq);
        int updateServerResponse = updateResponse.getStatusLine().getStatusCode();
        if (updateServerResponse != HttpStatus.SC_OK) {
            Log.e(THIS_FILE, "can't get updates from site : " + updateResponse.getStatusLine().getReasonPhrase()
                    + " - ");
            downloadError();
            return null;
        }

        updateResponseEntity = updateResponse.getEntity();
        BufferedReader upLineReader = new BufferedReader(
                new InputStreamReader(updateResponseEntity.getContent()), 2 * 1024);
        StringBuffer upBuf = new StringBuffer();
        String upLine;
        while ((upLine = upLineReader.readLine()) != null) {
            upBuf.append(upLine);
        }
        upLineReader.close();
        String content = upBuf.toString();
        try {
            JSONObject mainJSONObject = new JSONObject(content);

            JSONArray coreJSONArray = mainJSONObject.getJSONArray(for_what);

            JSONObject stack = getCompatibleStack(coreJSONArray);
            if (stack != null) {
                return new RemoteLibInfo(stack);
            }
        } catch (JSONException e) {
            Log.e(THIS_FILE, "Unable to parse " + content, e);
            downloadError();
        }

    } catch (ClientProtocolException e) {
        downloadError();
    } catch (IOException e) {
        downloadError();
    }

    return null;
}

From source file:org.commonjava.indy.client.core.IndyClientHttp.java

protected void addJsonHeaders(final HttpUriRequest req) {
    req.addHeader("Accept", "application/json");
    req.addHeader("Content-Type", "application/json");
}

From source file:com.baidu.asynchttpclient.AsyncHttpClient.java

private Future<?> sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest,
        String contentType, AsyncHttpResponseHandler responseHandler, Context context) {
    if (contentType != null) {
        uriRequest.addHeader("Content-Type", contentType);
    }//from  ww  w.j a v a  2 s .  com
    /*
     * ------------------ http header ----------------- uriRequest.addHeader("Platform", "8"); // ? 1=IOS
     * 8=Android uriRequest.addHeader("SDKVersion", NdCommplatformExtends.getInstance().getVersion()); // SDK??
     * uriRequest.addHeader("FWVersion", Utils.getDeviceSDKVersion()); // ? String model =
     * android.os.Build.MODEL; if(!TextUtils.isEmpty(model)) { if(model.length() > 10) { model =
     * model.substring(model.length() - 10); } uriRequest.addHeader("PhoneType", model); // ?(N97, Touch
     * HD10??10) } uriRequest.addHeader("Resolution", ScreenUtil.screen_width(context) + "x" +
     * ScreenUtil.screen_height(context)); // x640x960 uriRequest.addHeader("Network",
     * Utils.isWifi(context)? "1" : "0"); //  0=?WIFI 1=WIFI /* ------------------ http header
     * -----------------
     */

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }
    return request;
}

From source file:com.cloudmine.api.db.RequestDBObject.java

public HttpUriRequest toHttpRequest() {
    HttpUriRequest request = null;
    switch (requestType) {
    case GET:/*from  w  w  w. j a  va2  s  . c o  m*/
        request = new HttpGet(requestUrl);
        break;
    case PUT:
        request = new HttpPut(requestUrl);
        try {
            if (Strings.isNotEmpty(jsonBody)) {
                ((HttpPut) request).setEntity(new StringEntity(jsonBody));
                request.addHeader("Content-Type", "application/json");
            }
        } catch (UnsupportedEncodingException e) {
        }
        if (body != null && body.length < 0) {
            ((HttpPut) request).setEntity(new ByteArrayEntity(body));
        }
    }
    for (Header header : headers) {
        request.addHeader(header);
    }
    return request;
}

From source file:es.auth.plugin.JestHttpClient.java

public Tuple<JestResult, HttpResponse> executeE(final Action clientRequest) throws IOException {
    final String elasticSearchRestUrl = getRequestURL(getElasticSearchServer(), clientRequest.getURI());
    final HttpUriRequest request = constructHttpMethod(clientRequest.getRestMethodName(), elasticSearchRestUrl,
            clientRequest.getData(gson));
    log.debug("reqeust method and restUrl - " + clientRequest.getRestMethodName() + " " + elasticSearchRestUrl);
    // add headers added to action
    if (!clientRequest.getHeaders().isEmpty()) {
        for (final Iterator<Entry> it = clientRequest.getHeaders().entrySet().iterator(); it.hasNext();) {
            final Entry header = it.next();
            request.addHeader((String) header.getKey(), header.getValue().toString());
        }//from   w  w w. ja  v a 2  s  . c o m
    }
    final HttpResponse response = httpClient.execute(request);
    // If head method returns no content, it is added according to response code thanks to https://github.com/hlassiege
    if (request.getMethod().equalsIgnoreCase("HEAD")) {
        if (response.getEntity() == null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                response.setEntity(new StringEntity("{\"ok\" : true, \"found\" : true}"));
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                response.setEntity(new StringEntity("{\"ok\" : false, \"found\" : false}"));
            }
        }
    }
    return new Tuple(deserializeResponse(response, clientRequest), response);
}