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

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

Introduction

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

Prototype

@Deprecated
    public HttpParams getParams() 

Source Link

Usage

From source file:HybridIT.com.fourspaces.couchdb.Session.java

/**
* Method that actually performs the GET/PUT/POST/DELETE calls.
* Executes the given HttpMethod on the HttpClient object (one HttpClient per Session).
* <p>// w w  w  . ja  v  a 2s.  com
* This returns a CouchResponse, which can be used to get the status of the call (isOk), 
* and any headers / body that was sent back.
* 
* @param req
* @return the CouchResponse (status / error / json document)
*/
protected CouchResponse http(HttpRequestBase req) {

    HttpResponse httpResponse = null;
    HttpEntity entity = null;

    try {
        if (usesAuth) {
            req.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
        }
        httpResponse = httpClient.execute(req);
        entity = httpResponse.getEntity();
        lastResponse = new CouchResponse(req, httpResponse);
    } catch (IOException e) {
        log.error(ExceptionUtils.getStackTrace(e));
    } finally {
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    return lastResponse;
}

From source file:census.couchdroid.CouchSession.java

/**
 * Method that actually performs the GET/PUT/POST/DELETE calls.
 * Executes the given HttpMethod on the HttpClient object (one HttpClient per Session).
 * <p>/*from  w w w .  ja va 2 s  .co  m*/
 * This returns a CouchResponse, which can be used to get the status of the call (isOk), 
 * and any headers / body that was sent back.
 * 
 * @param req
 * @return the CouchResponse (status / error / json document)
 */
protected CouchResponse http(HttpRequestBase req) {
    HttpResponse httpResponse = null;
    HttpEntity entity = null;

    try {
        if (usesAuth) {
            req.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
        }
        httpResponse = httpClient.execute(req);

        entity = httpResponse.getEntity();
        lastResponse = new CouchResponse(req, httpResponse);

    } catch (IOException e) {
        android.util.Log.e("CouchSession", "Got exception: " + e.getMessage());
    } finally {
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    return lastResponse;
}

From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java

private <T> void contributeVirtualHost(final HttpRequestBase httpRequest,
        final HttpClientRequest<T> httpClientRequest) {
    final String virtualHost = httpClientRequest.getVirtualHost();
    if (StringUtils.isNotBlank(virtualHost)) {

        LOG.debug("Adding Virtual Host: '%s/%d'", virtualHost, httpClientRequest.getVirtualPort());

        httpRequest.getParams().setParameter(ClientPNames.VIRTUAL_HOST,
                new HttpHost(virtualHost, httpClientRequest.getVirtualPort()));
    }//w w w  . ja v  a 2  s. c  o m
}

From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java

private <T> void contributeParameters(final DefaultHttpClient httpClient, final HttpRequestBase httpRequest,
        final HttpClientRequest<T> httpClientRequest) {
    final Map<String, Object> parameters = httpClientRequest.getParameters();

    if (parameters != null && !parameters.isEmpty()) {
        HttpParams clientParams = httpClient.getParams();
        HttpParams requestParams = httpRequest.getParams();

        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            clientParams.setParameter(entry.getKey(), entry.getValue());
            requestParams.setParameter(entry.getKey(), entry.getValue());
        }//from w w  w .j  a v  a  2 s.  c  o m
    }
}

From source file:org.instagram4j.DefaultInstagramClient.java

@SuppressWarnings("unchecked")
private <T> Result<T[]> requestEntities(HttpRequestBase method, Class<T> type) throws InstagramException {
    method.getParams().setParameter("http.useragent", "Instagram4j/1.0");

    JsonParser jp = null;/*from   w ww. java  2s . com*/
    HttpResponse response = null;
    ResultMeta meta = null;

    try {
        method.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        setEnforceHeader(method);

        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 15000);
        client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 30000);

        if (LOG.isDebugEnabled())
            LOG.debug(String.format("Requesting entities entry point %s, method %s", method.getURI().toString(),
                    method.getMethod()));

        autoThrottle();

        response = client.execute(method);

        jp = createParser(response, method);

        JsonToken tok = jp.nextToken();
        if (tok != JsonToken.START_OBJECT) {
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                throw createInstagramException("Instagram request failed", method.getURI().toString(), response,
                        null, null);

            throw createInstagramException("Invalid response format from Instagram API",
                    method.getURI().toString(), response, null, null);
        }

        Pagination pagination = null;
        T[] data = null;

        while (true) {
            tok = jp.nextValue();
            if (tok == JsonToken.START_ARRAY) {
                // Should be "data"
                String name = jp.getCurrentName();
                if (!"data".equals(name))
                    throw createInstagramException("Unexpected field name " + name, method.getURI().toString(),
                            response, meta, null);

                List<T> items = new ArrayList<T>();

                tok = jp.nextToken();
                if (tok == JsonToken.START_OBJECT) {
                    if (type != null) {
                        T item;
                        while ((item = jp.readValueAs(type)) != null)
                            items.add(item);
                    } else
                        jp.readValueAs(Map.class); // Consume & ignore
                }

                data = (T[]) Array.newInstance(type, items.size());
                System.arraycopy(items.toArray(), 0, data, 0, items.size());
            } else if (tok == JsonToken.START_OBJECT) {
                // Should be "pagination" or "meta"
                String name = jp.getCurrentName();
                if ("pagination".equals(name))
                    pagination = jp.readValueAs(Pagination.class);
                else if ("meta".equals(name))
                    meta = jp.readValueAs(ResultMeta.class);
                else
                    throw createInstagramException("Unexpected field name " + name, method.getURI().toString(),
                            response, meta, null);
            } else
                break;
        }

        if (data == null && meta == null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
            throw createInstagramException("Instagram request failed", method.getURI().toString(), response,
                    null, null);

        Result<T[]> result = new Result<T[]>(pagination, meta, data);
        setRateLimits(response, result);

        return result;
    } catch (JsonParseException e) {
        throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } catch (JsonProcessingException e) {
        throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } catch (IOException e) {
        throw createInstagramException("Error communicating with Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } finally {
        if (jp != null)
            try {
                jp.close();
            } catch (IOException e) {
            }
        method.releaseConnection();
    }
}

From source file:com.sangupta.jerry.http.WebRequest.java

/**
* Create the {@link WebRequest} object using the given
* {@link HttpRequestBase} object./*from w w w. ja v  a  2 s  .  co  m*/
* 
* @param request
*            the base http request
* 
*/
WebRequest(final HttpRequestBase request) {
    super();
    this.request = request;
    this.localParams = request.getParams();
}

From source file:org.instagram4j.DefaultInstagramClient.java

private <T> Result<T> requestEntity(HttpRequestBase method, Class<T> type, boolean signableRequest)
        throws InstagramException {
    method.getParams().setParameter("http.useragent", "Instagram4j/1.0");

    JsonParser jp = null;/*from w w  w . ja  v  a 2  s .  co  m*/
    HttpResponse response = null;
    ResultMeta meta = null;

    try {
        method.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        if (signableRequest)
            setEnforceHeader(method);

        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 15000);
        client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 30000);

        if (LOG.isDebugEnabled())
            LOG.debug(String.format("Requesting entity entry point %s, method %s", method.getURI().toString(),
                    method.getMethod()));

        autoThrottle();

        response = client.execute(method);

        jp = createParser(response, method);

        JsonToken tok = jp.nextToken();
        if (tok != JsonToken.START_OBJECT) {
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                throw createInstagramException("Instagram request failed", method.getURI().toString(), response,
                        null, null);

            throw createInstagramException("Invalid response format from Instagram API",
                    method.getURI().toString(), response, null, null);
        }

        T data = null;

        while (true) {
            tok = jp.nextValue();
            if (tok == JsonToken.START_ARRAY) {
                throw createInstagramException("Unexpected array in entity response " + jp.getCurrentName(),
                        method.getURI().toString(), response, meta, null);
            } else if (tok == JsonToken.START_OBJECT) {
                // Should be "data" or "meta"
                String name = jp.getCurrentName();
                if ("meta".equals(name))
                    meta = jp.readValueAs(ResultMeta.class);
                else if ("data".equals(name)) {
                    if (type != null)
                        data = jp.readValueAs(type);
                    else
                        jp.readValueAs(Map.class); // Consume & ignore
                } else
                    throw createInstagramException("Unexpected field name " + name, method.getURI().toString(),
                            response, meta, null);
            } else
                break;
        }

        if (data == null && meta == null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
            throw createInstagramException("Instagram request failed", method.getURI().toString(), response,
                    null, null);

        Result<T> result = new Result<T>(null, meta, data);
        setRateLimits(response, result);

        return result;
    } catch (JsonParseException e) {
        throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } catch (JsonProcessingException e) {
        throw createInstagramException("Error parsing response from Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } catch (IOException e) {
        throw createInstagramException("Error communicating with Instagram: " + e.getMessage(),
                method.getURI().toString(), response, meta, e);
    } finally {
        if (jp != null)
            try {
                jp.close();
            } catch (IOException e) {
            }
        method.releaseConnection();
    }
}

From source file:net.oauth.client.httpclient4.HttpClient4.java

public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException {
    final String method = request.method;
    final String url = request.url.toExternalForm();
    final InputStream body = request.getBody();
    final boolean isDelete = DELETE.equalsIgnoreCase(method);
    final boolean isPost = POST.equalsIgnoreCase(method);
    final boolean isPut = PUT.equalsIgnoreCase(method);
    byte[] excerpt = null;
    HttpRequestBase httpRequest;
    if (isPost || isPut) {
        HttpEntityEnclosingRequestBase entityEnclosingMethod = isPost ? new HttpPost(url) : new HttpPut(url);
        if (body != null) {
            ExcerptInputStream e = new ExcerptInputStream(body);
            excerpt = e.getExcerpt();//  ww w .j a va 2  s.com
            String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH);
            entityEnclosingMethod
                    .setEntity(new InputStreamEntity(e, (length == null) ? -1 : Long.parseLong(length)));
        }
        httpRequest = entityEnclosingMethod;
    } else if (isDelete) {
        httpRequest = new HttpDelete(url);
    } else {
        httpRequest = new HttpGet(url);
    }
    for (Map.Entry<String, String> header : request.headers) {
        httpRequest.addHeader(header.getKey(), header.getValue());
    }
    HttpParams params = httpRequest.getParams();
    for (Map.Entry<String, Object> p : parameters.entrySet()) {
        String name = p.getKey();
        String value = p.getValue().toString();
        if (FOLLOW_REDIRECTS.equals(name)) {
            params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.parseBoolean(value));
        } else if (READ_TIMEOUT.equals(name)) {
            params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, Integer.parseInt(value));
        } else if (CONNECT_TIMEOUT.equals(name)) {
            params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Integer.parseInt(value));
        }
    }
    HttpClient client = clientPool.getHttpClient(new URL(httpRequest.getURI().toString()));
    HttpResponse httpResponse = client.execute(httpRequest);
    return new HttpMethodResponse(httpRequest, httpResponse, excerpt, request.getContentCharset());
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

public void collect() {
    if (isPingCompat.get()) {
        // back compat w/ old url.availability templates
        super.collect();
        return;//from www.j a v a 2s  . c  o m
    }
    this.matches.clear();
    HttpConfig config = new HttpConfig(getTimeoutMillis(), getTimeoutMillis(), proxyHost.get(),
            proxyPort.get());
    AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig();
    log.debug("isAcceptUnverifiedCert:" + keystoreConfig.isAcceptUnverifiedCert());
    HQHttpClient client = new HQHttpClient(keystoreConfig, config, keystoreConfig.isAcceptUnverifiedCert());
    HttpParams params = client.getParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, useragent.get());
    if (this.hosthdr != null) {
        params.setParameter(ClientPNames.VIRTUAL_HOST, this.hosthdr);
    }
    HttpRequestBase request;
    double avail = 0;
    try {
        if (getMethod().equals(HttpHead.METHOD_NAME)) {
            request = new HttpHead(getURL());
            addParams(request, this.params.get());
        } else if (getMethod().equals(HttpPost.METHOD_NAME)) {
            HttpPost httpPost = new HttpPost(getURL());
            request = httpPost;
            addParams(httpPost, this.params.get());
        } else {
            request = new HttpGet(getURL());
            addParams(request, this.params.get());
        }
        request.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, isFollow());
        addCredentials(request, client);
        startTime();
        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        int tries = 0;
        while (statusCode == HttpURLConnection.HTTP_MOVED_TEMP && tries < 3) {
            tries++;
            Header header = response.getFirstHeader("Location");
            String url = header.getValue();
            String[] toks = url.split(";");
            String[] t = toks.length > 1 ? toks[1].split("\\?") : new String[0];
            response = getRedirect(toks[0], t.length > 1 ? t[1] : "");
            statusCode = response.getStatusLine().getStatusCode();
        }
        endTime();
        setResponseCode(statusCode);
        avail = getAvail(statusCode);
        StringBuilder msg = new StringBuilder(String.valueOf(statusCode));
        Header header = response.getFirstHeader("Server");
        msg.append(header != null ? " (" + header.getValue() + ")" : "");
        setLastModified(response, statusCode);
        avail = checkPattern(response, avail, msg);
        setAvailMsg(avail, msg);
    } catch (UnsupportedEncodingException e) {
        log.error("unsupported encoding: " + e, e);
    } catch (IOException e) {
        avail = Metric.AVAIL_DOWN;
        setErrorMessage(e.toString());
    } finally {
        setAvailability(avail);
    }
    netstat();
}

From source file:de.escidoc.core.common.util.service.ConnectionUtility.java

/**
 * //from ww  w.  j  a v a 2 s.c  o m
 * @param request
 * @param cookie
 * @return The response of the request.
 * @throws WebserverSystemException
 */
private HttpResponse executeRequest(final DefaultHttpClient client, final HttpRequestBase request,
        final URL url, final Cookie cookie, final String username, final String password)
        throws WebserverSystemException {
    try {
        request.setURI(url.toURI());

        if (cookie != null) {
            HttpClientParams.setCookiePolicy(request.getParams(), CookiePolicy.BEST_MATCH);
            request.setHeader("Cookie", cookie.getName() + '=' + cookie.getValue());
        }

        final DefaultHttpClient clientToUse = client == null ? getHttpClient() : client;

        if (PROXY_HOST != null && isProxyRequired(url)) {
            clientToUse.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, PROXY_HOST);
        }

        if (username != null && password != null) {
            setAuthentication(clientToUse, url, username, password);
        }

        final HttpResponse httpResponse = clientToUse.execute(request);

        final int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (responseCode / HTTP_RESPONSE_CLASS != HttpServletResponse.SC_OK / HTTP_RESPONSE_CLASS) {
            final String errorPage = readResponse(httpResponse);
            throw new WebserverSystemException(
                    "HTTP connection to \"" + request.getURI().toString() + "\" failed: " + errorPage);
        }

        return httpResponse;
    } catch (final IOException e) {
        throw new WebserverSystemException(e);
    } catch (final URISyntaxException e) {
        throw new WebserverSystemException("Illegal URL '" + url + "'.", e);
    }
}