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:com.testlinkrestapi.restclient.RestClient.java

private String doRequest(HttpUriRequest req) throws RestException, IOException {
    req.addHeader("Accept", "application/json");
    HttpResponse resp = httpClient.execute(req);
    HttpEntity ent = resp.getEntity();//from  w w w.  j a v  a 2s  .co m
    StringBuilder result = new StringBuilder();

    if (ent != null) {
        String encoding = null;
        if (ent.getContentEncoding() != null) {
            encoding = ent.getContentEncoding().getValue();
        }

        if (encoding == null) {
            Header contentTypeHeader = resp.getFirstHeader("Content-Type");
            HeaderElement[] contentTypeElements = contentTypeHeader.getElements();
            for (HeaderElement he : contentTypeElements) {
                NameValuePair nvp = he.getParameterByName("charset");
                if (nvp != null) {
                    encoding = nvp.getValue();
                }
            }
        }

        InputStreamReader isr = encoding != null ? new InputStreamReader(ent.getContent(), encoding)
                : new InputStreamReader(ent.getContent());
        BufferedReader br = new BufferedReader(isr);
        String line = "";

        while ((line = br.readLine()) != null)
            result.append(line);
    }
    //  System.out.println(result.toString());
    StatusLine sl = resp.getStatusLine();

    if (sl.getStatusCode() >= 300)
        throw new RestException(sl.getReasonPhrase(), sl.getStatusCode(), result.toString());

    return result.length() > 0 ? result.toString() : null;
}

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

private String request(HttpUriRequest req) throws RestException, IOException {
    req.addHeader("Accept", "application/json");
    HttpResponse resp = httpClient.execute(req);
    HttpEntity ent = resp.getEntity();/*from w w  w.j ava  2  s.  c o m*/
    StringBuilder result = new StringBuilder();

    if (ent != null) {
        String encoding = null;
        if (ent.getContentEncoding() != null) {
            encoding = ent.getContentEncoding().getValue();
        }

        if (encoding == null) {
            Header contentTypeHeader = resp.getFirstHeader("Content-Type");
            HeaderElement[] contentTypeElements = contentTypeHeader.getElements();
            for (HeaderElement he : contentTypeElements) {
                NameValuePair nvp = he.getParameterByName("charset");
                if (nvp != null) {
                    encoding = nvp.getValue();
                }
            }
        }

        InputStreamReader isr = encoding != null ? new InputStreamReader(ent.getContent(), encoding)
                : new InputStreamReader(ent.getContent());
        BufferedReader br = new BufferedReader(isr);
        String line = "";

        while ((line = br.readLine()) != null)
            result.append(line);
    }

    StatusLine sl = resp.getStatusLine();

    if (sl.getStatusCode() >= 300)
        throw new RestException(sl.getReasonPhrase(), sl.getStatusCode(), result.toString());
    return result.length() > 0 ? result.toString() : null;

    //return result.length() > 0 ? JSONSerializer.toJSON(result.toString()): null;
}

From source file:com.demo.wtm.service.RestService.java

private HttpUriRequest addHeaderParams(HttpUriRequest request) throws Exception {
    for (NameValuePair h : headers) {
        request.addHeader(h.getName(), h.getValue());
    }//from  www.j  a  v a 2 s . c  o  m

    WtmPreference wp = new WtmPreference(context);
    authtoken = wp.getString("authtoken", "");

    if (authentication) {
        request.setHeader("X-ZUMO-APPLICATION", "wMaoPxwwslHHzDTejLrObxTljWXxvT36");
        request.setHeader("X-ZUMO-AUTH", authtoken);
    }

    return request;
}

From source file:com.example.aab119.restclientexample.RestClient.java

private HttpUriRequest addHeaderParams(HttpUriRequest request) throws Exception {
    for (NameValuePair h : headers) {
        request.addHeader(h.getName(), h.getValue());
    }/*from  w w  w.j ava 2 s .  com*/

    if (authentication) {

        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
        request.addHeader(new BasicScheme().authenticate(creds, request));
    }

    return request;
}

From source file:com.betaplay.sdk.http.HttpClient.java

private HttpUriRequest addBodyParams(HttpUriRequest request) throws Exception {
    if (mJsonBody != null) {
        request.addHeader("Content-Type", "application/json");
        if (request instanceof HttpPost) {
            ((HttpPost) request).setEntity(new StringEntity(mJsonBody, "UTF-8"));
        }/*from w  ww  .j a v a  2s.c o  m*/
    }
    return request;
}

From source file:se.inera.certificate.proxy.mappings.remote.RemoteDispatcher.java

private void addHeaders(HttpServletRequest request, HttpUriRequest req) {
    for (String headerName : list(request.getHeaderNames())) {
        if (!BLOCKED_HEADERS.contains(lowerCase(headerName))) {
            req.addHeader(headerName, request.getHeader(headerName));
        }/*from   ww  w.  ja va 2s  .c o m*/
    }
    for (Map.Entry<String, String> headers : getRequestContext().getHeaders(request).entrySet()) {
        req.setHeader(headers.getKey(), headers.getValue());
    }
}

From source file:org.droidparts.http.worker.HttpClientWorker.java

private HttpResponse getHttpResponse(HttpUriRequest req) throws HTTPException {
    for (String key : headers.keySet()) {
        for (String val : headers.get(key)) {
            req.addHeader(key, val);
        }/*from   ww  w .j  a v  a  2  s  .  c om*/
    }
    req.setHeader("Accept-Encoding", "gzip,deflate");
    try {
        return httpClient.execute(req);
    } catch (Exception e) {
        throw new HTTPException(e);
    }
}

From source file:com.microsoft.services.odata.unittests.testsupport.WireMockTestClient.java

private WireMockResponse executeMethodAndCovertExceptions(HttpUriRequest httpRequest,
        TestHttpHeader... headers) {/*  ww  w  . j  av a 2  s  . c  o m*/
    try {
        for (TestHttpHeader header : headers) {
            httpRequest.addHeader(header.getName(), header.getValue());
        }
        HttpResponse httpResponse = httpClient().execute(httpRequest);
        return new WireMockResponse(httpResponse);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:vn.mbm.phimp.me.gallery3d.picasa.GDataClient.java

private void callMethod(HttpUriRequest request, Operation operation) throws IOException {
    // Specify GData protocol version 2.0.
    request.addHeader("GData-Version", "2");

    // Indicate support for gzip-compressed responses.
    request.addHeader("Accept-Encoding", "gzip");

    // Specify authorization token if provided.
    String authToken = mAuthToken;
    if (!TextUtils.isEmpty(authToken)) {
        request.addHeader("Authorization", "GoogleLogin auth=" + authToken);
    }//from  w w  w  . ja  v  a  2  s.com

    // Specify the ETag of a prior response, if available.
    String etag = operation.inOutEtag;
    if (etag != null) {
        request.addHeader("If-None-Match", etag);
    }

    // Execute the HTTP request.
    HttpResponse httpResponse = null;
    try {
        httpResponse = mHttpClient.execute(request);
    } catch (IOException e) {
        Log.w(TAG, "Request failed: " + request.getURI());
        throw e;
    }

    // Get the status code and response body.
    int status = httpResponse.getStatusLine().getStatusCode();
    InputStream stream = null;
    HttpEntity entity = httpResponse.getEntity();
    if (entity != null) {
        // Wrap the entity input stream in a GZIP decoder if necessary.
        stream = entity.getContent();
        if (stream != null) {
            Header header = entity.getContentEncoding();
            if (header != null) {
                if (header.getValue().contains("gzip")) {
                    stream = new GZIPInputStream(stream);
                }
            }
        }
    }

    // Return the stream if successful.
    Header etagHeader = httpResponse.getFirstHeader("ETag");
    operation.outStatus = status;
    operation.inOutEtag = etagHeader != null ? etagHeader.getValue() : null;
    operation.outBody = stream;
}

From source file:ch.cyberduck.core.sds.SDSReadFeature.java

@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback)
        throws BackgroundException {
    try {/*w  w  w . j a va2 s  .c  o  m*/
        final SDSApiClient client = session.getClient();
        final HttpUriRequest request = new HttpGet(
                String.format("%s/nodes/files/%s/downloads", client.getBasePath(),
                        new SDSNodeIdProvider(session).getFileid(file, new DisabledListProgressListener())));
        request.addHeader("X-Sds-Auth-Token", StringUtils.EMPTY);
        if (status.isAppend()) {
            final HttpRange range = HttpRange.withStatus(status);
            final String header;
            if (-1 == range.getEnd()) {
                header = String.format("bytes=%d-", range.getStart());
            } else {
                header = String.format("bytes=%d-%d", range.getStart(), range.getEnd());
            }
            if (log.isDebugEnabled()) {
                log.debug(String.format("Add range header %s for file %s", header, file));
            }
            request.addHeader(new BasicHeader(HttpHeaders.RANGE, header));
            // Disable compression
            request.addHeader(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "identity"));
        }
        final HttpResponse response = client.getClient().execute(request);
        switch (response.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_PARTIAL_CONTENT:
            return new HttpMethodReleaseInputStream(response);
        default:
            throw new HttpResponseExceptionMappingService().map(new HttpResponseException(
                    response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
        }
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map("Download {0} failed", e, file);
    }
}