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

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

Introduction

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

Prototype

public void setHeader(String str, String str2) 

Source Link

Usage

From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java

private static ApptentiveHttpResponse performHttpRequest(String oauthToken, String uri, Method method,
        String body) {//w ww  .j  a v  a2s  . c om
    Log.d("Performing request to %s", uri);
    //Log.e("OAUTH Token: %s", oauthToken);

    ApptentiveHttpResponse ret = new ApptentiveHttpResponse();
    HttpClient httpClient = null;
    try {
        HttpRequestBase request;
        httpClient = new DefaultHttpClient();
        switch (method) {
        case GET:
            request = new HttpGet(uri);
            break;
        case PUT:
            request = new HttpPut(uri);
            request.setHeader("Content-Type", "application/json");
            Log.d("PUT body: " + body);
            ((HttpPut) request).setEntity(new StringEntity(body, "UTF-8"));
            break;
        case POST:
            request = new HttpPost(uri);
            request.setHeader("Content-Type", "application/json");
            Log.d("POST body: " + body);
            ((HttpPost) request).setEntity(new StringEntity(body, "UTF-8"));
            break;
        default:
            Log.e("Unrecognized method: " + method.name());
            return ret;
        }

        HttpParams httpParams = request.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_HTTP_CONNECT_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_HTTP_SOCKET_TIMEOUT);
        httpParams.setParameter("http.useragent", getUserAgentString());
        request.setHeader("Authorization", "OAuth " + oauthToken);
        request.setHeader("Accept-Encoding", "gzip");
        request.setHeader("Accept", "application/json");
        request.setHeader("X-API-Version", API_VERSION);

        HttpResponse response = httpClient.execute(request);
        int code = response.getStatusLine().getStatusCode();
        ret.setCode(code);
        ret.setReason(response.getStatusLine().getReasonPhrase());
        Log.d("Response Status Line: " + response.getStatusLine().toString());

        HeaderIterator headerIterator = response.headerIterator();
        if (headerIterator != null) {
            Map<String, String> headers = new HashMap<String, String>();
            while (headerIterator.hasNext()) {
                Header header = (Header) headerIterator.next();
                headers.put(header.getName(), header.getValue());
                //Log.v("Header: %s = %s", header.getName(), header.getValue());
            }
            ret.setHeaders(headers);
        }

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream is = entity.getContent();
            if (is != null) {
                String contentEncoding = ret.getHeaders().get("Content-Encoding");
                if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
                    is = new GZIPInputStream(is);
                }
                ret.setContent(Util.readStringFromInputStream(is, "UTF-8"));
                if (code >= 200 && code < 300) {
                    Log.d("Response: " + ret.getContent());
                } else {
                    Log.w("Response: " + ret.getContent());
                }
            }
        }
    } catch (IllegalArgumentException e) {
        Log.w("Error communicating with server.", e);
    } catch (SocketTimeoutException e) {
        Log.w("Timeout communicating with server.");
    } catch (IOException e) {
        Log.w("Error communicating with server.", e);
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return ret;
}

From source file:org.wso2.carbon.appmgt.mdm.restconnector.utils.RestUtils.java

/**
 * Execute HTTP method and return whether operation success or not.
 *
 * @param remoteServer Bean that holds information about remote server
 * @param httpClient HTTP client object//from   www. j a  v a  2 s .co  m
 * @param httpRequestBase HTTP method which should be executed
 * @return true if HTTP method successfully executed false if not
 */
public static String executeMethod(RemoteServer remoteServer, HttpClient httpClient,
        HttpRequestBase httpRequestBase) {
    String authKey = getAPIToken(remoteServer, false);
    HttpResponse response = null;
    String responseString = null;
    if (log.isDebugEnabled()) {
        log.debug("Access token received : " + authKey);
    }

    try {
        int statusCode = 401;
        int tries = 0;
        while (statusCode != 200) {

            if (log.isDebugEnabled()) {
                log.debug("Trying to call API : trying for " + (tries + 1) + " time(s).");
            }

            httpRequestBase.setHeader(Constants.RestConstants.AUTHORIZATION,
                    Constants.RestConstants.BEARER + authKey);
            if (log.isDebugEnabled()) {
                log.debug("Sending " + httpRequestBase.getMethod() + " request to " + httpRequestBase.getURI());
            }

            response = httpClient.execute(httpRequestBase);
            statusCode = response.getStatusLine().getStatusCode();
            if (log.isDebugEnabled()) {
                log.debug("Status code received : " + statusCode);
            }

            if (++tries >= 3) {
                log.info("API Call failed for the 3rd time: No or Unauthorized Access Aborting.");
                return null;
            }
            if (statusCode == 401) {
                authKey = getAPIToken(remoteServer, true);
                if (log.isDebugEnabled()) {
                    log.debug("Access token getting again, Access token received :  " + authKey + " in  try "
                            + tries + ".");
                }
            }
        }
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            responseString = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
        }
        return responseString;
    } catch (IOException e) {
        String errorMessage = "No OK response received form the API.";
        log.error(errorMessage, e);
        return null;
    }
}

From source file:es.bsc.demiurge.core.utils.HttpUtils.java

/**
 * Builds an HTTP Request./*w ww . j  a  va2s  . c o  m*/
 *
 * @param methodType Type of the request (GET, POST, etc.).
 * @param uri URI of the request.
 * @param header Headers of the request.
 * @param entity Entity of the request.
 * @return The HTTP Request built.
 */
public static HttpRequestBase buildHttpRequest(String methodType, URI uri, Map<String, String> header,
        String entity) {
    HttpRequestBase request;

    //instantiate the request according to its type (GET, POST...)
    switch (methodType) {
    case "GET":
        request = new HttpGet(uri);
        break;
    case "POST":
        request = new HttpPost(uri);
        break;
    case "DELETE":
        request = new HttpDelete(uri);
        break;
    default:
        request = null;
        break;
    }

    if (request == null) {
        throw new IllegalArgumentException("Method not supported.");
    }

    //set the headers of the request
    for (Map.Entry<String, String> entry : header.entrySet()) {
        request.setHeader(entry.getKey(), entry.getValue());
    }

    //if the type of the request is POST, set the entity of the request
    if (request instanceof HttpPost && !entity.equals("")) {
        try {
            ((HttpPost) request).setEntity(new StringEntity(entity));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    return request;
}

From source file:com.vuze.android.remote.rpc.RestJsonClient.java

public static Map<?, ?> connect(String id, String url, Map<?, ?> jsonPost, Header[] headers,
        UsernamePasswordCredentials creds, boolean sendGzip) throws RPCException {
    long readTime = 0;
    long connSetupTime = 0;
    long connTime = 0;
    int bytesRead = 0;
    if (DEBUG_DETAILED) {
        Log.d(TAG, id + "] Execute " + url);
    }/*from  w  w  w  .  jav a 2s .co m*/
    long now = System.currentTimeMillis();
    long then;

    Map<?, ?> json = Collections.EMPTY_MAP;

    try {

        URI uri = new URI(url);
        int port = uri.getPort();

        BasicHttpParams basicHttpParams = new BasicHttpParams();
        HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote");

        DefaultHttpClient httpclient;
        if ("https".equals(uri.getScheme())) {
            httpclient = MySSLSocketFactory.getNewHttpClient(port);
        } else {
            httpclient = new DefaultHttpClient(basicHttpParams);
        }

        //AndroidHttpClient.newInstance("Vuze Android Remote");

        // This doesn't set the "Authorization" header!?
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), creds);

        // Prepare a request object
        HttpRequestBase httpRequest = jsonPost == null ? new HttpGet(uri) : new HttpPost(uri); // IllegalArgumentException

        if (creds != null) {
            byte[] toEncode = (creds.getUserName() + ":" + creds.getPassword()).getBytes();
            String encoding = Base64Encode.encodeToString(toEncode, 0, toEncode.length);
            httpRequest.setHeader("Authorization", "Basic " + encoding);
        }

        if (jsonPost != null) {
            HttpPost post = (HttpPost) httpRequest;
            String postString = JSONUtils.encodeToJSON(jsonPost);
            if (AndroidUtils.DEBUG_RPC) {
                Log.d(TAG, id + "]  Post: " + postString);
            }

            AbstractHttpEntity entity = (sendGzip && Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
                    ? getCompressedEntity(postString)
                    : new StringEntity(postString);
            post.setEntity(entity);

            post.setHeader("Accept", "application/json");
            post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
            setupRequestFroyo(httpRequest);
        }

        if (headers != null) {
            for (Header header : headers) {
                httpRequest.setHeader(header);
            }
        }

        // Execute the request
        HttpResponse response;

        then = System.currentTimeMillis();
        if (AndroidUtils.DEBUG_RPC) {
            connSetupTime = (then - now);
            now = then;
        }

        httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
                if (i < 2) {
                    return true;
                }
                return false;
            }
        });
        response = httpclient.execute(httpRequest);

        then = System.currentTimeMillis();
        if (AndroidUtils.DEBUG_RPC) {
            connTime = (then - now);
            now = then;
        }

        HttpEntity entity = response.getEntity();

        // XXX STATUSCODE!

        StatusLine statusLine = response.getStatusLine();
        if (AndroidUtils.DEBUG_RPC) {
            Log.d(TAG, "StatusCode: " + statusLine.getStatusCode());
        }

        if (entity != null) {

            long contentLength = entity.getContentLength();
            if (contentLength >= Integer.MAX_VALUE - 2) {
                throw new RPCException("JSON response too large");
            }

            // A Simple JSON Response Read
            InputStream instream = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
                    ? getUngzippedContent(entity)
                    : entity.getContent();
            InputStreamReader isr = new InputStreamReader(instream, "utf8");

            StringBuilder sb = null;
            BufferedReader br = null;
            // JSONReader is 10x slower, plus I get more OOM errors.. :(
            //            final boolean useStringBuffer = contentLength > (4 * 1024 * 1024) ? false
            //                  : DEFAULT_USE_STRINGBUFFER;
            final boolean useStringBuffer = DEFAULT_USE_STRINGBUFFER;

            if (useStringBuffer) {
                // Setting capacity saves StringBuffer from going through many
                // enlargeBuffers, and hopefully allows toString to not make a copy
                sb = new StringBuilder(contentLength > 512 ? (int) contentLength + 2 : 512);
            } else {
                if (AndroidUtils.DEBUG_RPC) {
                    Log.d(TAG, "Using BR. ContentLength = " + contentLength);
                }
                br = new BufferedReader(isr, 8192);
                br.mark(32767);
            }

            try {

                // 9775 files on Nexus 7 (~2,258,731 bytes)
                // fastjson 1.1.46 (String)       :  527- 624ms
                // fastjson 1.1.39 (String)       :  924-1054ms
                // fastjson 1.1.39 (StringBuilder): 1227-1463ms
                // fastjson 1.1.39 (BR)           : 2233-2260ms
                // fastjson 1.1.39 (isr)          :      2312ms
                // GSON 2.2.4 (String)            : 1539-1760ms
                // GSON 2.2.4 (BufferedReader)    : 2646-3060ms
                // JSON-SMART 1.3.1 (String)      :  572- 744ms (OOMs more often than fastjson)

                if (useStringBuffer) {
                    char c[] = new char[8192];
                    while (true) {
                        int read = isr.read(c);
                        if (read < 0) {
                            break;
                        }
                        sb.append(c, 0, read);
                    }

                    if (AndroidUtils.DEBUG_RPC) {
                        then = System.currentTimeMillis();
                        if (DEBUG_DETAILED) {
                            if (sb.length() > 2000) {
                                Log.d(TAG, id + "] " + sb.substring(0, 2000) + "...");
                            } else {
                                Log.d(TAG, id + "] " + sb.toString());
                            }
                        }
                        bytesRead = sb.length();
                        readTime = (then - now);
                        now = then;
                    }

                    json = JSONUtils.decodeJSON(sb.toString());
                    //json = JSONUtilsGSON.decodeJSON(sb.toString());
                } else {

                    //json = JSONUtils.decodeJSON(isr);
                    json = JSONUtils.decodeJSON(br);
                    //json = JSONUtilsGSON.decodeJSON(br);
                }

            } catch (Exception pe) {

                //               StatusLine statusLine = response.getStatusLine();
                if (statusLine != null && statusLine.getStatusCode() == 409) {
                    throw new RPCException(response, "409");
                }

                try {
                    String line;
                    if (useStringBuffer) {
                        line = sb.subSequence(0, Math.min(128, sb.length())).toString();
                    } else {
                        br.reset();
                        line = br.readLine().trim();
                    }

                    isr.close();

                    if (AndroidUtils.DEBUG_RPC) {
                        Log.d(TAG, id + "]line: " + line);
                    }
                    Header contentType = entity.getContentType();
                    if (line.startsWith("<") || line.contains("<html")
                            || (contentType != null && contentType.getValue().startsWith("text/html"))) {
                        // TODO: use android strings.xml
                        throw new RPCException(response,
                                "Could not retrieve remote client location information.  The most common cause is being on a guest wifi that requires login before using the internet.");
                    }
                } catch (IOException ignore) {

                }

                Log.e(TAG, id, pe);
                if (statusLine != null) {
                    String msg = statusLine.getStatusCode() + ": " + statusLine.getReasonPhrase() + "\n"
                            + pe.getMessage();
                    throw new RPCException(msg, pe);
                }
                throw new RPCException(pe);
            } finally {
                closeOnNewThread(useStringBuffer ? isr : br);
            }

            if (AndroidUtils.DEBUG_RPC) {
                //               Log.d(TAG, id + "]JSON Result: " + json);
            }

        }
    } catch (RPCException e) {
        throw e;
    } catch (Throwable e) {
        Log.e(TAG, id, e);
        throw new RPCException(e);
    }

    if (AndroidUtils.DEBUG_RPC) {
        then = System.currentTimeMillis();
        Log.d(TAG, id + "] conn " + connSetupTime + "/" + connTime + "ms. Read " + bytesRead + " in " + readTime
                + "ms, parsed in " + (then - now) + "ms");
    }
    return json;
}

From source file:com.bigdata.rockstor.console.RockStorSender.java

private static HttpRequestBase buildHttpRequest(HttpReq req)
        throws UnsupportedEncodingException, URISyntaxException {

    HttpRequestBase request = null;
    if ("GET".equals(req.getMethod())) {
        request = new HttpGet();
    } else if ("PUT".equals(req.getMethod())) {
        request = new HttpPut();
        if (req.getBody() != null && req.getBody().length() > 0)
            ((HttpPut) request).setEntity(new StringEntity(req.getBody()));
    } else if ("DELETE".equals(req.getMethod())) {
        request = new HttpDelete();
    } else if ("HEAD".equals(req.getMethod())) {
        request = new HttpHead();
    } else {/*  ww  w.j a v  a 2 s  .  c  o  m*/
        throw new NullPointerException("Unknown HTTP Method : " + req.getMethod());
    }

    request.setURI(new URI(req.getUrl()));

    if (req.getHead() != null) {
        for (Map.Entry<String, String> e : req.getHead().entrySet()) {
            if ("PUT".equals(req.getMethod()) && e.getKey().equals("Content-Length"))
                continue;
            request.setHeader(e.getKey(), e.getValue());
        }
    }

    return request;
}

From source file:im.delight.faceless.APIRequest.java

@Override
protected void addCustomHTTPHeaders(HttpRequestBase request) {
    request.setHeader(HTTP_HEADER_API_SIGNATURE, getRequestSignature());
    request.setHeader(HTTP_HEADER_API_TIMESTAMP, mTimestamp);
}

From source file:com.sonyericsson.android.drm.drmlicenseservice.DLSHttpClient.java

private static void addParameters(Bundle parameters, HttpRequestBase request) {
    if (parameters != null && request != null) {
        Bundle headers = parameters.getBundle(Constants.DRM_KEYPARAM_HTTP_HEADERS);
        if (headers != null && headers.size() > 0) {
            for (String headerKey : headers.keySet()) {
                if (headerKey != null && headerKey.length() > 0) {
                    String headerValue = headers.getString(headerKey);
                    if (headerValue != null && headerValue.length() > 0) {
                        request.setHeader(headerKey, headerValue);
                    }//  www  . jav  a2  s .  com
                }
            }
        }
    }
}

From source file:immf.ImodeNetClient.java

private static void addDumyHeader(HttpRequestBase req) {
    req.setHeader("Accept", "*/*");
    req.setHeader("Accept-Encoding", "gzip, deflate");
    req.setHeader("Cache-Control", "no-cache");
    req.setHeader("User-Agent", "Mozilla/4.0 (compatible;MSIE 7.0; Windows NT 6.0;)");
    req.setHeader("x-pw-service", "PCMAIL/1.0");
    req.setHeader("Referer", "https://imode.net/imail/oexaf/ahtm/index_f.html");
}

From source file:net.mindengine.isolator4j.ResourceTestBase.java

private Response executeRequest(HttpRequestBase httpRequestBase) throws IOException {
    httpRequestBase.setHeader("Content-Type", "application/json");
    httpRequestBase.setHeader("Cookie", getMockCookieName() + "=" + mockUniqueKey);
    HttpResponse response = client.execute(httpRequestBase);
    int code = response.getStatusLine().getStatusCode();
    String textResponse = IOUtils.toString(response.getEntity().getContent());
    return new Response(code, textResponse);
}

From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java

/**
 * TODO - REDIRECTION output:: if there was no redirection, should just show
 * the actual initial URL?//ww w .  j a v a 2  s . c o m
 *
 * @param httpRequest
 * @param acceptHeaderValue
 */
private static HTTPRequestResponse performHTTPRequest(ClientConnectionManager connectionManager,
        HttpRequestBase httpRequest, RESTActivityConfigurationBean configBean,
        Map<String, String> urlParameters, CredentialsProvider credentialsProvider) {
    // headers are set identically for all HTTP methods, therefore can do
    // centrally - here

    // If the user wants to set MIME type for the 'Accepts' header
    String acceptsHeaderValue = configBean.getAcceptsHeaderValue();
    if ((acceptsHeaderValue != null) && !acceptsHeaderValue.isEmpty()) {
        httpRequest.setHeader(ACCEPT_HEADER_NAME, URISignatureHandler.generateCompleteURI(acceptsHeaderValue,
                urlParameters, configBean.getEscapeParameters()));
    }

    // See if user wanted to set any other HTTP headers
    ArrayList<ArrayList<String>> otherHTTPHeaders = configBean.getOtherHTTPHeaders();
    if (!otherHTTPHeaders.isEmpty())
        for (ArrayList<String> httpHeaderNameValuePair : otherHTTPHeaders)
            if (httpHeaderNameValuePair.get(0) != null && !httpHeaderNameValuePair.get(0).isEmpty()) {
                String headerParameterizedValue = httpHeaderNameValuePair.get(1);
                String headerValue = URISignatureHandler.generateCompleteURI(headerParameterizedValue,
                        urlParameters, configBean.getEscapeParameters());
                httpRequest.setHeader(httpHeaderNameValuePair.get(0), headerValue);
            }

    try {
        HTTPRequestResponse requestResponse = new HTTPRequestResponse();
        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, null);
        ((DefaultHttpClient) httpClient).setCredentialsProvider(credentialsProvider);
        HttpContext localContext = new BasicHttpContext();

        // Set the proxy settings, if any
        if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).isEmpty()) {
            // Instruct HttpClient to use the standard
            // JRE proxy selector to obtain proxy information
            ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                    httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
            httpClient.setRoutePlanner(routePlanner);
            // Do we need to authenticate the user to the proxy?
            if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).isEmpty())
                // Add the proxy username and password to the list of
                // credentials
                httpClient.getCredentialsProvider().setCredentials(
                        new AuthScope(System.getProperty(PROXY_HOST),
                                Integer.parseInt(System.getProperty(PROXY_PORT))),
                        new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME),
                                System.getProperty(PROXY_PASSWORD)));
        }

        // execute the request
        HttpResponse response = httpClient.execute(httpRequest, localContext);

        // record response code
        requestResponse.setStatusCode(response.getStatusLine().getStatusCode());
        requestResponse.setReasonPhrase(response.getStatusLine().getReasonPhrase());

        // record header values for Content-Type of the response
        requestResponse.setResponseContentTypes(response.getHeaders(CONTENT_TYPE_HEADER_NAME));

        // track where did the final redirect go to (if there was any)
        HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest targetRequest = (HttpUriRequest) localContext
                .getAttribute(ExecutionContext.HTTP_REQUEST);
        requestResponse.setRedirectionURL("" + targetHost + targetRequest.getURI());
        requestResponse.setRedirectionHTTPMethod(targetRequest.getMethod());
        requestResponse.setHeaders(response.getAllHeaders());

        /* read and store response body
         (check there is some content - negative length of content means
         unknown length;
         zero definitely means no content...)*/
        // TODO - make sure that this test is sufficient to determine if
        // there is no response entity
        if (response.getEntity() != null && response.getEntity().getContentLength() != 0)
            requestResponse.setResponseBody(readResponseBody(response.getEntity()));

        // release resources (e.g. connection pool, etc)
        httpClient.getConnectionManager().shutdown();
        return requestResponse;
    } catch (Exception ex) {
        return new HTTPRequestResponse(ex);
    }
}