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.apache.asterix.test.aql.TestExecutor.java

private HttpUriRequest constructGetMethod(String endpoint, OutputFormat fmt,
        List<CompilationUnit.Parameter> params) {

    HttpUriRequest method = constructGetMethod(endpoint, params);
    // Set accepted output response type
    method.setHeader("Accept", fmt.mimeType());
    return method;
}

From source file:org.apache.asterix.test.aql.TestExecutor.java

private HttpUriRequest constructPostMethod(String endpoint, OutputFormat fmt,
        List<CompilationUnit.Parameter> params) {

    HttpUriRequest method = constructPostMethod(endpoint, params);
    // Set accepted output response type
    method.setHeader("Accept", fmt.mimeType());
    return method;
}

From source file:org.apache.asterix.test.aql.TestExecutor.java

public InputStream executeQuery(String str, OutputFormat fmt, String url,
        List<CompilationUnit.Parameter> params) throws Exception {
    HttpUriRequest method = constructHttpMethod(str, url, "query", false, params);
    // Set accepted output response type
    method.setHeader("Accept", fmt.mimeType());
    HttpResponse response = executeAndCheckHttpRequest(method);
    return response.getEntity().getContent();
}

From source file:org.mumod.util.HttpManager.java

public InputStream requestData(String url, String httpMethod, ArrayList<NameValuePair> params, int loop)
        throws IOException, MustardException, AuthException {

    URI uri;/*from  ww w  . j  a va2s  .c o  m*/

    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL.");
    }
    if (MustardApplication.DEBUG)
        Log.d("HTTPManager", "Requesting " + uri);
    HttpUriRequest method;

    if (POST.equals(httpMethod)) {
        HttpPost post = new HttpPost(uri);
        if (params != null)
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        method = post;
    } else if (DELETE.equals(httpMethod)) {
        method = new HttpDelete(uri);
    } else {
        method = new HttpGet(uri);
    }

    if (mHeaders != null) {
        Iterator<String> headKeys = mHeaders.keySet().iterator();
        while (headKeys.hasNext()) {
            String key = headKeys.next();
            method.setHeader(key, mHeaders.get(key));
        }
    }
    if (consumer != null) {
        try {
            consumer.sign(method);
        } catch (OAuthMessageSignerException e) {

        } catch (OAuthExpectationFailedException e) {

        } catch (OAuthCommunicationException e) {

        }
    }

    HttpResponse response;
    try {
        response = mClient.execute(method);
    } catch (ClientProtocolException e) {
        throw new IOException("HTTP protocol error.");
    }

    int statusCode = response.getStatusLine().getStatusCode();
    //      Log.d("HttpManager", url + " >> " + statusCode);
    if (statusCode == 401) {
        throw new AuthException(401, "Unauthorized");
    } else if (statusCode == 400 || statusCode == 403 || statusCode == 406) {
        try {
            JSONObject json = null;
            try {
                json = new JSONObject(StreamUtil.toString(response.getEntity().getContent()));
            } catch (JSONException e) {
                throw new MustardException(998, "Non json response: " + e.toString());
            }
            throw new MustardException(statusCode, json.getString("error"));
        } catch (IllegalStateException e) {
            throw new IOException("Could not parse error response.");
        } catch (JSONException e) {
            throw new IOException("Could not parse error response.");
        }
    } else if (statusCode == 404) {
        // User/Group or page not found
        throw new MustardException(404, "Not found: " + url);
    } else if ((statusCode == 301 || statusCode == 302 || statusCode == 303) && GET.equals(httpMethod)
            && loop < 3) {
        //         Log.v("HttpManager", "Got : " + statusCode);
        Header hLocation = response.getLastHeader("Location");
        if (hLocation != null) {
            Log.v("HttpManager", "Got : " + hLocation.getValue());
            return requestData(hLocation.getValue(), httpMethod, params, loop + 1);
        } else
            throw new MustardException(statusCode, "Too many redirect: " + url);
    } else if (statusCode != 200) {
        throw new MustardException(999, "Unmanaged response code: " + statusCode);
    }

    return response.getEntity().getContent();
}

From source file:com.enjoy.nerd.http.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single requests
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete,
 *                        HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 *//*from   w  w w .ja  v a2  s .co  m*/
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    //tangwh  add, ?????cookie?cookie?setCookieStore?uriRequestHeader?
    //??http2Cookie???cookieStore
    client.setCookieStore(null);

    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 new RequestHandle(request);
}

From source file:org.mustard.util.HttpManager.java

public InputStream requestData(String url, String httpMethod, ArrayList<NameValuePair> params, int loop)
        throws IOException, MustardException, AuthException {

    URI uri;//from   ww w. j a  v a 2  s.  c om

    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL.");
    }
    if (MustardApplication.DEBUG)
        Log.d("HTTPManager", "Requesting " + uri);
    HttpUriRequest method;

    if (POST.equals(httpMethod)) {
        HttpPost post = new HttpPost(uri);
        if (params != null)
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        method = post;
    } else if (DELETE.equals(httpMethod)) {
        method = new HttpDelete(uri);
    } else {
        method = new HttpGet(uri);
    }

    if (mHeaders != null) {
        Iterator<String> headKeys = mHeaders.keySet().iterator();
        while (headKeys.hasNext()) {
            String key = headKeys.next();
            method.setHeader(key, mHeaders.get(key));
        }
    }
    if (consumer != null) {
        try {
            consumer.sign(method);
        } catch (OAuthMessageSignerException e) {

        } catch (OAuthExpectationFailedException e) {

        } catch (OAuthCommunicationException e) {

        }
    }

    HttpResponse response;
    try {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        String accessToken = preferences.getString("oauth2_access_token", "no token specified");
        method.setHeader("Authorization", "Bearer " + accessToken);
        response = mClient.execute(method);
    } catch (ClientProtocolException e) {
        throw new IOException("HTTP protocol error.");
    }

    int statusCode = response.getStatusLine().getStatusCode();
    //      Log.d("HttpManager", url + " >> " + statusCode);
    if (statusCode == 401) {
        throw new AuthException(401, "Unauthorized");
    } else if (statusCode == 403 || statusCode == 406) {
        try {
            JSONObject json = null;
            try {
                json = new JSONObject(StreamUtil.toString(response.getEntity().getContent()));
            } catch (JSONException e) {
                throw new MustardException(998, "Non json response: " + e.toString());
            }
            throw new MustardException(statusCode, json.getString("error"));
        } catch (IllegalStateException e) {
            throw new IOException("Could not parse error response.");
        } catch (JSONException e) {
            throw new IOException("Could not parse error response.");
        }
    } else if (statusCode == 404) {
        // User/Group or page not found
        throw new MustardException(404, "Not found: " + url);
    } else if ((statusCode == 301 || statusCode == 302 || statusCode == 303) && GET.equals(httpMethod)
            && loop < 3) {
        //         Log.v("HttpManager", "Got : " + statusCode);
        Header hLocation = response.getLastHeader("Location");
        if (hLocation != null) {
            Log.v("HttpManager", "Got : " + hLocation.getValue());
            return requestData(hLocation.getValue(), httpMethod, params, loop + 1);
        } else
            throw new MustardException(statusCode, "Too many redirect: " + url);
    } else if (statusCode != 200) {
        throw new MustardException(999, "Unmanaged response code: " + statusCode);
    }

    return response.getEntity().getContent();
}

From source file:com.flyn.net.asynchttp.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single
 *                        requests//from   ww w . j av a  2s  .  c o m
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of
 *                        request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of
 *                        HttpDelete, HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 */
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    AsyncHttpRequest request = new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler);
    threadPool.submit(request);
    RequestHandle requestHandle = new RequestHandle(request);

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

        requestList.add(requestHandle);

        Iterator<RequestHandle> iterator = requestList.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().shouldBeGarbageCollected()) {
                iterator.remove();
            }
        }
    }

    return requestHandle;
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

private void setHeaders(final HttpUriRequest httpUriRequest) {
    if (this.headers != null) {
        for (final Entry<String, String> entry : this.headers) {
            httpUriRequest.setHeader(entry.getKey(), entry.getValue());
        }//from ww  w.  ja va2s. c  om
    }
    if (this.host != null)
        httpUriRequest.setHeader(HTTP.TARGET_HOST, this.host);
    httpUriRequest.setHeader(HTTP.CONN_DIRECTIVE, "close"); // don't keep alive, prevent CLOSE_WAIT state
}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java

protected CloseableHttpResponse execute(HttpUriRequest httpMethod) throws HttpException, IOException {
    setHeaders(httpMethod);/*  w  ww .  j  ava  2s. c om*/
    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 = httpConfiguration == null ? null
            : httpConfiguration.getMethodConfiguration(httpMethod);

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

    localContext.setRequestConfig(requestConfigBuilder.build());

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

        if (credentialsProvider.getCredentials(targetScope) != null) {
            BasicScheme targetAuth = new BasicScheme();
            targetAuth.processChallenge(new BasicHeader(AUTH.WWW_AUTH, "BASIC preemptive"));
            authCache.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);
                }

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

    return CLIENT.execute(httpMethod, localContext);
}

From source file:org.jets3t.service.impl.rest.httpclient.GoogleStorageService.java

/**
 * Authorizes an HTTP/S request using the standard HMAC approach or OAuth 2,
 * whichever technique is appropriate.//from  w  ww.  j  a v  a 2  s.c  o  m
 *
 * @param httpMethod
 * the request object
 * @param context
 * @param ignoredForceRequestSignatureVersion
 * ignored parameter relevant only for AWS4-HMAC-SHA256 request signing.
 * @throws ServiceException
 */
@Override
public void authorizeHttpRequest(HttpUriRequest httpMethod, HttpContext context,
        String ignoredForceRequestSignatureVersion) throws ServiceException {
    if (getProviderCredentials() instanceof OAuth2Credentials) {
        OAuth2Tokens tokens;
        try {
            tokens = ((OAuth2Credentials) getProviderCredentials()).getOAuth2Tokens();
        } catch (IOException e) {
            throw new ServiceException("Failure retrieving OAuth2 tokens", e);
        }
        if (tokens == null) {
            throw new ServiceException("Cannot authenticate using OAuth2 until initial tokens are provided"
                    + ", i.e. via setOAuth2Tokens()");
        }
        log.debug("Authorizing service request with OAuth2 access token: " + tokens.getAccessToken());
        httpMethod.setHeader("Authorization", "OAuth " + tokens.getAccessToken());
        httpMethod.setHeader("x-goog-api-version", "2");
    } else {
        super.authorizeHttpRequest(httpMethod, context, ignoredForceRequestSignatureVersion);
    }
}