Example usage for org.apache.http.client HttpClient getParams

List of usage examples for org.apache.http.client HttpClient getParams

Introduction

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

Prototype

@Deprecated
HttpParams getParams();

Source Link

Document

Obtains the parameters for this client.

Usage

From source file:bg.fourweb.android.rss.Parser.java

public Feed parse(final String url, ProgressObserver obs) {
    final HttpClient client = CompatHttp.getHttpClient();

    // configure the HTTP client
    client.getParams().setIntParameter("http.socket.timeout", opts.getConnectionTimeout());

    try {//from   w ww .  j  av  a  2s.  c o m
        final HttpUriRequest get = new HttpGet(url);
        final HttpResponse resp = client.execute(get);

        // prepare content length (it's needed for progress indication)
        int contentLength = 0;
        final Header[] contentLengthHeaders = resp.getHeaders("Content-Length");
        if (ArrayUtils.isEmpty(contentLengthHeaders) == false) {
            final Header contentLengthHeader = contentLengthHeaders[0];
            final String contentLengthValue = contentLengthHeader.getValue();
            if (StringUtils.isEmpty(contentLengthValue) == false) {
                try {
                    contentLength = Integer.parseInt(contentLengthValue);
                } catch (NumberFormatException ignored) {
                    // NOP
                }
            }
        }

        // prepare progress observers
        final ProgressInputStream body = new ProgressInputStream(resp.getEntity().getContent(), contentLength);
        if (obs != null) {
            body.addProgressObserver(obs);
        }

        // handler
        h = prepareHandler();

        // parse
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        parser.parse(body, h);
        return h.getProductFeed();
    } catch (Throwable e) {
        if (DBG) {
            Log.w(TAG, "", e);
        }
    } finally {
        CompatHttp.closeHttpClient(client);
    }
    return null;
}

From source file:org.eoc.sdk.Dispatcher.java

private boolean doRequest(HttpRequestBase requestBase) {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), mTimeOut);
    HttpResponse response;/*www  .j a v  a 2 s . c om*/

    if (mEoc.isDryRun()) {
        Logy.d(LOGGER_TAG, "DryRun, stored HttpRequest, now " + mDryRunOutput.size());
        mDryRunOutput.add(requestBase);
    } else {
        if (!mDryRunOutput.isEmpty())
            mDryRunOutput.clear();
        try {
            response = client.execute(requestBase);
            int statusCode = response.getStatusLine().getStatusCode();
            Logy.d(LOGGER_TAG, String.format("status code %s", statusCode));
            return statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_OK;
        } catch (Exception e) {
            Logy.w(LOGGER_TAG, "Cannot send request", e);
        }
    }
    return false;
}

From source file:org.piwik.sdk.Dispatcher.java

private boolean doRequest(HttpRequestBase requestBase) {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), mTimeOut);
    HttpResponse response;//from  w w w . j a  v  a2  s .  co m

    if (mPiwik.isDryRun()) {
        Logy.d(LOGGER_TAG, "DryRun, stored HttpRequest, now " + mDryRunOutput.size());
        mDryRunOutput.add(requestBase);
    } else {
        if (!mDryRunOutput.isEmpty())
            mDryRunOutput.clear();
        try {
            response = client.execute(requestBase);
            int statusCode = response.getStatusLine().getStatusCode();
            Logy.d(LOGGER_TAG, String.format("status code %s", statusCode));
            return statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_OK;
        } catch (Exception e) {
            Logy.w(LOGGER_TAG, "Cannot send request", e);
        }
    }
    return false;
}

From source file:org.wso2.identity.integration.test.oauth2.OAuth2RequestObjectSignatureValidationTestCase.java

private HttpClient getRedirectDisabledClient() {

    HttpClient client = new DefaultHttpClient();
    HttpClientParams.setRedirecting(client.getParams(), false);
    return client;
}

From source file:net.sourceforge.subsonic.backend.controller.IPNController.java

private boolean validate(String url) throws Exception {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 60000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 60000);
    HttpGet method = new HttpGet(url);
    String content;/*from   w w  w  .j  a  v a  2  s .  c  om*/
    try {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        content = client.execute(method, responseHandler);

        LOG.info("Validation result: " + content);
        return "VERIFIED".equals(content);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.gitblit.plugin.flowdock.FlowDock.java

/**
 * Send a payload message.//from  w  ww .  java 2  s .c o  m
 *
 * @param payload
 * @throws IOException
 */
public void send(Payload payload) throws IOException {

    String flow = payload.getFlow();
    String token;

    if (StringUtils.isEmpty(flow)) {
        // default flow
        token = runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_TOKEN, null);
    } else {
        // specified flow, validate token
        token = runtimeManager.getSettings().getString(String.format(Plugin.SETTING_FLOW_TOKEN, flow), null);
        if (StringUtils.isEmpty(token)) {
            token = runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_TOKEN, null);
            log.warn("No FlowDock API token specified for '{}', defaulting to default flow'",
                    payload.getFlow());
            log.warn("Please set '{} = TOKEN' in gitblit.properties",
                    String.format(Plugin.SETTING_FLOW_TOKEN, flow));
        }
    }

    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GmtDateTypeAdapter()).create();
    String json = gson.toJson(payload);
    log.debug(json);

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

    String flowdockUrl = payload.getEndPoint(token);
    HttpPost post = new HttpPost(flowdockUrl);
    post.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NAME + "/" + Constants.getVersion());
    post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    if (payload.postForm()) {
        // post as a form with a "payload" value
        List<NameValuePair> nvps = new ArrayList<NameValuePair>(1);
        nvps.add(new BasicNameValuePair("payload", json));
        post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
    } else {
        // post as JSON
        StringEntity entity = new StringEntity(json, "UTF-8");
        entity.setContentType("application/json");
        post.setEntity(entity);
    }

    HttpResponse response = client.execute(post);
    int rc = response.getStatusLine().getStatusCode();

    if (HttpStatus.SC_OK == rc) {
        // This is the expected result code
        // replace this with post.closeConnection() after JGit updates to HttpClient 4.2
        post.abort();
    } else {
        String result = null;
        InputStream is = response.getEntity().getContent();
        try {
            byte[] buffer = new byte[8192];
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int len = 0;
            while ((len = is.read(buffer)) > -1) {
                os.write(buffer, 0, len);
            }
            result = os.toString("UTF-8");
        } finally {
            if (is != null) {
                is.close();
            }
        }

        log.error("FlowDock plugin sent:");
        log.error(json);
        log.error("FlowDock returned:");
        log.error(result);

        throw new IOException(String.format("FlowDock Error (%s): %s", rc, result));
    }
}

From source file:com.nextgis.maplib.datasource.ngw.Connection.java

public HttpClient getHttpClient() {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, APP_USER_AGENT);
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT_CONNECTION);
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT_SOKET);
    httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);

    return httpclient;
}

From source file:net.datacrow.onlinesearch.discogs.task.DiscogsMusicSearch.java

private HttpClient getHttpClient() {
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "DataCrow/4.0 +http://www.datacrow.net");
    return httpClient;
}

From source file:com.github.seratch.signedrequest4j.SignedRequestApacheHCImpl.java

@Override
public HttpResponse doRequest(String url, HttpMethod method, RequestBody body, String charset)
        throws IOException {

    HttpClient httpClient = new DefaultHttpClient();
    HttpUriRequest request = getRequest(method, url);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeoutMillis);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeoutMillis);
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);
    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset);

    for (String name : headersToOverwrite.keySet()) {
        request.setHeader(name, headersToOverwrite.get(name));
    }//from w ww  .  jav  a 2 s. c o  m

    String oAuthNonce = String.valueOf(new SecureRandom().nextLong());
    Long oAuthTimestamp = System.currentTimeMillis() / 1000;
    String signature = getSignature(url, method, oAuthNonce, oAuthTimestamp);
    String authorizationHeader = getAuthorizationHeader(signature, oAuthNonce, oAuthTimestamp);
    request.setHeader("Authorization", authorizationHeader);

    if (method == HttpMethod.POST) {
        HttpPost postRequest = (HttpPost) request;
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(new ByteArrayInputStream(body.getBody()));
        entity.setContentType(body.getContentType());
        postRequest.setEntity(entity);
    } else if (method == HttpMethod.PUT) {
        HttpPut putRequest = (HttpPut) request;
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(new ByteArrayInputStream(body.getBody()));
        entity.setContentType(body.getContentType());
        putRequest.setEntity(entity);
    }

    org.apache.http.HttpResponse apacheHCResponse = httpClient.execute(request);
    if (apacheHCResponse.getStatusLine().getStatusCode() >= 400) {
        HttpResponse httpResponse = toReturnValue(apacheHCResponse, charset);
        throw new HttpException(apacheHCResponse.getStatusLine().getReasonPhrase(), httpResponse);
    }
    return toReturnValue(apacheHCResponse, charset);
}

From source file:org.dspace.submit.lookup.PubmedService.java

public List<Record> search(String query) throws IOException, HttpException {
    List<Record> results = new ArrayList<>();
    if (!ConfigurationManager.getBooleanProperty(SubmissionLookupService.CFG_MODULE, "remoteservice.demo")) {
        HttpGet method = null;/*from ww  w.  jav  a  2s  .  c o  m*/
        try {
            HttpClient client = new DefaultHttpClient();
            client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

            URIBuilder uriBuilder = new URIBuilder("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi");
            uriBuilder.addParameter("db", "pubmed");
            uriBuilder.addParameter("datetype", "edat");
            uriBuilder.addParameter("retmax", "10");
            uriBuilder.addParameter("term", query);
            method = new HttpGet(uriBuilder.build());

            // Execute the method.
            HttpResponse response = client.execute(method);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                throw new RuntimeException("WS call failed: " + statusLine);
            }

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);
            factory.setIgnoringElementContentWhitespace(true);

            DocumentBuilder builder;
            try {
                builder = factory.newDocumentBuilder();

                Document inDoc = builder.parse(response.getEntity().getContent());

                Element xmlRoot = inDoc.getDocumentElement();
                Element idList = XMLUtils.getSingleElement(xmlRoot, "IdList");
                List<String> pubmedIDs = XMLUtils.getElementValueList(idList, "Id");
                results = getByPubmedIDs(pubmedIDs);
            } catch (ParserConfigurationException e1) {
                log.error(e1.getMessage(), e1);
            } catch (SAXException e1) {
                log.error(e1.getMessage(), e1);
            }
        } catch (Exception e1) {
            log.error(e1.getMessage(), e1);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
    } else {
        InputStream stream = null;
        try {
            File file = new File(ConfigurationManager.getProperty("dspace.dir")
                    + "/config/crosswalks/demo/pubmed-search.xml");
            stream = new FileInputStream(file);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);
            factory.setIgnoringElementContentWhitespace(true);

            DocumentBuilder builder = factory.newDocumentBuilder();
            Document inDoc = builder.parse(stream);

            Element xmlRoot = inDoc.getDocumentElement();
            Element idList = XMLUtils.getSingleElement(xmlRoot, "IdList");
            List<String> pubmedIDs = XMLUtils.getElementValueList(idList, "Id");
            results = getByPubmedIDs(pubmedIDs);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return results;
}