Example usage for org.apache.http.params CoreConnectionPNames CONNECTION_TIMEOUT

List of usage examples for org.apache.http.params CoreConnectionPNames CONNECTION_TIMEOUT

Introduction

In this page you can find the example usage for org.apache.http.params CoreConnectionPNames CONNECTION_TIMEOUT.

Prototype

String CONNECTION_TIMEOUT

To view the source code for org.apache.http.params CoreConnectionPNames CONNECTION_TIMEOUT.

Click Source Link

Usage

From source file:base.tina.external.http.HttpTask.java

@Override
public final void run() throws Exception {
    if (httpPlugin == null || httpPlugin.url == null)
        return;/*from  w  ww .  ja  v  a2 s .co m*/
    //#debug 
    base.tina.core.log.LogPrinter.d(null, "-----------" + httpPlugin.url + "-----------");
    httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    HttpResponse response;

    if (httpPlugin.requestData == null && httpPlugin.requestDataInputStream == null) {
        HttpGet getRequest = new HttpGet(URI.create(httpPlugin.url));
        request = getRequest;
        response = httpClient.execute(getRequest);
    } else {
        HttpPost requestPost = new HttpPost(URI.create(httpPlugin.url));

        request = requestPost;

        // request.setHeader("Connention", "close");

        if (httpPlugin.requestDataInputStream != null) {
            InputStream instream = httpPlugin.requestDataInputStream;
            InputStreamEntity inputStreamEntity = new InputStreamEntity(instream, httpPlugin.dataLength);
            requestPost.setEntity(inputStreamEntity);
        } else {
            InputStream instream = new ByteArrayInputStream(httpPlugin.requestData);
            InputStreamEntity inputStreamEntity = new InputStreamEntity(instream,
                    httpPlugin.requestData.length);
            requestPost.setEntity(inputStreamEntity);
        }
        response = httpClient.execute(requestPost);
    }
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        httpPlugin.parseData(EntityUtils.toByteArray(response.getEntity()));
        commitResult(httpPlugin, CommitAction.WAKE_UP);
    } else {
        //#debug error
        base.tina.core.log.LogPrinter.e(null,
                "Http error : " + new String(EntityUtils.toByteArray(response.getEntity())));
        throw new Exception("Http response code is : " + response.getStatusLine().getStatusCode());
    }
}

From source file:org.codegist.crest.io.http.HttpClientHttpChannelTest.java

@Test
public void setConnetionTimeoutShouldSetHttpClientRequestParams() throws IOException {
    HttpParams params = mock(HttpParams.class);
    when(request.getParams()).thenReturn(params);
    toTest.setConnectionTimeout(123);/*from  www .  ja  va  2 s . c  om*/
    verify(params).setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 123);
}

From source file:de.hybris.platform.mpintgproductcockpit.productcockpit.util.HttpInvoker.java

public String post(final String reqURL, final String reqStr, final String charset, final int timeout) {
    // Prepare HTTP post
    final HttpPost post = new HttpPost(reqURL);
    post.setHeader("Content-Type", "application/json");

    // set content type as json and charset
    final StringEntity reqEntity = new StringEntity(reqStr, ContentType.create("application/json", charset));
    post.setEntity(reqEntity);//w  w w .  j  a  va2s  . c  o m

    // Create HTTP client
    final HttpClient httpClient = new DefaultHttpClient();

    // set connection over time
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(timeout / 2));
    // set data loading over time
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(timeout / 2));

    // Execute request
    try {
        final HttpResponse response = httpClient.execute(post);
        // get response and return as String
        final HttpEntity responseEntity = response.getEntity();
        return EntityUtils.toString(responseEntity);
    } catch (final Exception e) {
        return null;
    } finally {
        post.releaseConnection();
    }
}

From source file:org.xwiki.extension.repository.xwiki.internal.httpclient.DefaultHttpClientFactory.java

@Override
public HttpClient createClient(String user, String password) {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, this.configuration.getUserAgent());
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

    // Setup proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Setup authentication
    if (user != null) {
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, password));
    }/*from www.ja  va 2 s .  com*/

    return httpClient;
}

From source file:at.ac.univie.isc.asio.integration.IntegrationTest.java

@BeforeClass
public static void restAssuredDefaults() {
    RestAssured.config = RestAssured.config()
            .httpClient(HttpClientConfig.httpClientConfig()
                    .setParam(CoreConnectionPNames.CONNECTION_TIMEOUT, 30_000)
                    .setParam(CoreConnectionPNames.SO_TIMEOUT, 30_000))
            .encoderConfig(EncoderConfig.encoderConfig().defaultContentCharset(Charsets.UTF_8.name()).and()
                    .defaultQueryParameterCharset(Charsets.UTF_8.name()).and()
                    .appendDefaultContentCharsetToContentTypeIfUndefined(false))
            .matcherConfig(/*from w  ww.  j av  a  2  s.co m*/
                    new MatcherConfig().errorDescriptionType(MatcherConfig.ErrorDescriptionType.HAMCREST))
            .sslConfig(SSLConfig.sslConfig().relaxedHTTPSValidation());
}

From source file:org.niceday.AsyncHttpPost.java

@Override
public void run() {
    try {//from ww  w  . ja  v a2 s .c om
        request = new HttpPost(url);
        Log.d(AsyncHttpPost.class.getName(), "AsyncHttpGet  request to url :" + url);
        request.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        request.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
        if (parameter != null && parameter.size() > 0) {
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            for (RequestParameter p : parameter) {
                list.add(new BasicNameValuePair(p.getName(), p.getValue()));
            }
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        }
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            ByteArrayOutputStream content = new ByteArrayOutputStream();
            response.getEntity().writeTo(content);
            String ret = new String(content.toByteArray()).trim();
            content.close();
            Object Object = null;
            if (AsyncHttpPost.this.handler != null) {
                Object = AsyncHttpPost.this.handler.handle(ret);
                if (AsyncHttpPost.this.requestCallback != null && Object != null) {
                    AsyncHttpPost.this.requestCallback.onSuccess(Object);
                    return;
                }
                if (Object == null || "".equals(Object.toString())) {
                    RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                            "");
                    AsyncHttpPost.this.requestCallback.onFail(exception);
                }
            } else {
                AsyncHttpPost.this.requestCallback.onSuccess(ret);
            }
        } else {
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "," + statusCode);
            AsyncHttpPost.this.requestCallback.onFail(exception);
        }

        Log.d(AsyncHttpPost.class.getName(), "AsyncHttpGet  request to url :" + url + "  finished !");
    } catch (java.lang.IllegalArgumentException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpGet.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION,
                "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  UnsupportedEncodingException  " + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION, "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION,
                "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        e.printStackTrace();
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "");
        AsyncHttpPost.this.requestCallback.onFail(exception);
        e.printStackTrace();
        Log.d(AsyncHttpPost.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  IOException  " + e.getMessage());
    } finally {
        //request.
    }
    super.run();
}

From source file:fr.cph.stock.android.web.Connect.java

protected String connectUrl(String adress) throws IOException {
    String toreturn = null;/*w ww.j ava  2s . c o m*/
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    Log.d(TAG, "adress: " + adress);
    HttpGet get = new HttpGet(adress);
    HttpResponse getResponse = client.execute(get);
    HttpEntity responseEntity = getResponse.getEntity();

    Charset charset = Charset.forName("UTF8");
    InputStreamReader in = new InputStreamReader(responseEntity.getContent(), charset);
    int c = in.read();
    StringBuilder build = new StringBuilder();
    while (c != -1) {
        build.append((char) c);
        c = in.read();
    }
    toreturn = build.toString();
    return toreturn;
}

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

public List<Record> search(Context context, Set<String> dois, String apiKey)
        throws HttpException, IOException, JDOMException, ParserConfigurationException, SAXException {
    List<Record> results = new ArrayList<Record>();
    if (dois != null && dois.size() > 0) {
        for (String record : dois) {
            try {
                HttpGet method = null;// w w  w  .j  ava2s  .  c  o m
                try {
                    HttpClient client = new DefaultHttpClient();
                    client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

                    try {
                        URIBuilder uriBuilder = new URIBuilder("http://www.crossref.org/openurl/");
                        uriBuilder.addParameter("pid", apiKey);
                        uriBuilder.addParameter("noredirect", "true");
                        uriBuilder.addParameter("id", record);
                        method = new HttpGet(uriBuilder.build());
                    } catch (URISyntaxException ex) {
                        throw new HttpException("Request not sent", ex);
                    }

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

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

                    Record crossitem;
                    try {
                        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                        factory.setValidating(false);
                        factory.setIgnoringComments(true);
                        factory.setIgnoringElementContentWhitespace(true);

                        DocumentBuilder db = factory.newDocumentBuilder();
                        Document inDoc = db.parse(response.getEntity().getContent());

                        Element xmlRoot = inDoc.getDocumentElement();
                        Element queryResult = XMLUtils.getSingleElement(xmlRoot, "query_result");
                        Element body = XMLUtils.getSingleElement(queryResult, "body");
                        Element dataRoot = XMLUtils.getSingleElement(body, "query");

                        crossitem = CrossRefUtils.convertCrossRefDomToRecord(dataRoot);
                        results.add(crossitem);
                    } catch (Exception e) {
                        log.warn(LogManager.getHeader(context, "retrieveRecordDOI",
                                record + " DOI is not valid or not exist: " + e.getMessage()));
                    }
                } finally {
                    if (method != null) {
                        method.releaseConnection();
                    }
                }
            } catch (RuntimeException rt) {
                log.error(rt.getMessage(), rt);
            }
        }
    }
    return results;
}

From source file:uk.ac.ox.oucs.vle.XcriPopulatorInput.java

public void init() {
    // We will have multiple threads using the same httpClient.
    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "SES Import")
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout)
            .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
}

From source file:org.eclipse.lyo.oslc4j.bugzilla.utils.BugzillaHttpClient.java

private static HttpClient getHttpClient() {
    SSLContext sc = getTrustingSSLContext();
    SchemeSocketFactory sf = new SSLSocketFactory(sc);

    Scheme scheme = new Scheme("https", 443, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(scheme);/*from w  ww  .  j  av  a 2  s  . c o m*/

    sf = PlainSocketFactory.getSocketFactory();
    scheme = new Scheme("http", 80, sf);

    schemeRegistry.register(scheme);

    ClientConnectionManager clientConnectionManager = new PoolingClientConnectionManager(schemeRegistry);
    HttpParams clientParams = new BasicHttpParams();

    clientParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT);
    clientParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT);
    clientParams.setParameter(ClientPNames.HANDLE_REDIRECTS, true);

    return new DefaultHttpClient(clientConnectionManager, clientParams);
}