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

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

Introduction

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

Prototype

String SO_TIMEOUT

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

Click Source Link

Usage

From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status)
        throws ClientProtocolException, IOException {

    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }//from w  w  w  . j ava2  s .  c om

    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }

    }

    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }

    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }

    if (ah != null) {
        ah.applyToken(this, hr);
    }

    DefaultHttpClient client = getClient();

    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }

    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    request = hr;

    if (abort) {
        throw new IOException("Aborted");
    }

    HttpResponse response = null;

    try {
        //response = client.execute(hr, context);
        response = execute(hr, client, context);
    } catch (HttpHostConnectException e) {

        //if proxy is used, automatically retry without proxy
        if (proxy != null) {
            AQUtility.debug("proxy failed, retrying without proxy");
            hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
            //response = client.execute(hr, context);
            response = execute(hr, client, context);
        } else {
            throw e;
        }
    }

    byte[] data = null;

    String redirect = url;

    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;

    HttpEntity entity = response.getEntity();

    File file = null;

    if (code < 200 || code >= 300) {

        InputStream is = null;

        try {

            if (entity != null) {

                is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);

                error = new String(s, "UTF-8");

                AQUtility.debug("error", error);

            }
        } catch (Exception e) {
            AQUtility.debug(e);
        } finally {
            AQUtility.close(is);
        }

    } else {

        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();

        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));

        OutputStream os = null;
        InputStream is = null;

        try {
            file = getPreFile();

            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }

            is = entity.getContent();
            if ("gzip".equalsIgnoreCase(getEncoding(entity))) {
                is = new GZIPInputStream(is);
            }

            copy(is, os, (int) entity.getContentLength());

            os.flush();

            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }

        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }

    }

    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }

    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file)
            .client(client).context(context).headers(response.getAllHeaders());

}

From source file:org.openrdf.http.client.SparqlSession.java

/**
 * Gets the http connection read timeout in milliseconds.
 *//*  w w w  . j  a  v  a 2s. c o m*/
public long getConnectionTimeout() {
    return (long) params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0);
}

From source file:org.openrdf.http.client.SparqlSession.java

/**
 * Sets the http connection read timeout.
 * //from   w  ww  . j av  a  2  s. com
 * @param timeout
 *        timeout in milliseconds. Zero sets to infinity.
 */
public void setConnectionTimeout(long timeout) {
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, (int) timeout);
}

From source file:org.dasein.cloud.vcloud.vCloudMethod.java

protected @Nonnull HttpClient getClient(boolean forAuthentication) throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new CloudException("No context was defined for this request");
    }/* ww  w  . ja  v a2s  .  c o  m*/
    String endpoint = ctx.getCloud().getEndpoint();

    if (endpoint == null) {
        throw new CloudException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");
    int targetPort;
    URI uri;

    try {
        uri = new URI(endpoint);
        targetPort = uri.getPort();
        if (targetPort < 1) {
            targetPort = (ssl ? 443 : 80);
        }
    } catch (URISyntaxException e) {
        throw new CloudException(e);
    }
    HttpHost targetHost = new HttpHost(uri.getHost(), targetPort, uri.getScheme());
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");

    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (provider.isInsecure()) {
        try {
            client.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {

                        public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                                throws CertificateException {
                            return true;
                        }
                    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    if (forAuthentication) {
        String accessPublic = null;
        String accessPrivate = null;
        try {
            List<ContextRequirements.Field> fields = provider.getContextRequirements().getConfigurableValues();
            for (ContextRequirements.Field f : fields) {
                if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) {
                    byte[][] keyPair = (byte[][]) provider.getContext().getConfigurationValue(f);
                    accessPublic = new String(keyPair[0], "utf-8");
                    accessPrivate = new String(keyPair[1], "utf-8");
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new InternalException(e);
        }
        String password = accessPrivate;
        String userName;

        if (matches(getAPIVersion(), "0.8", "0.8")) {
            userName = accessPublic;
        } else {
            userName = accessPublic + "@" + ctx.getAccountNumber();
        }

        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));
    }
    return client;
}

From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java

/**
 * Gets the http connection read timeout in milliseconds.
 *///w ww. ja v  a 2s.com
public long getConnectionTimeout() {
    if (params == null) {
        return 0;
    }
    return (long) params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0);
}

From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java

/**
 * Sets the http connection read timeout.
 * /* w  w  w.  j av  a2s  . c om*/
 * @param timeout
 *        timeout in milliseconds. Zero sets to infinity.
 */
public void setConnectionTimeout(long timeout) {
    if (params == null) {
        params = new BasicHttpParams();
    }
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, (int) timeout);
}

From source file:com.groupon.odo.bmp.http.BrowserMobHttpClient.java

public void setSocketOperationTimeout(int readTimeout) {
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Makes a Http operation./*w w w  .j a va  2 s.co  m*/
 * 
 * This method set a parameters to the request that avoid being waiting 
 * for the server response or once connected, being waiting to receive 
 * the data.
 * 
 * @param method      Method type to execute. @See HTTP_METHOD.
 * @param url         Url of the request.
 * @param jsonData      The body content of the request (JSON). Can be null.
 * @param headers      The headers to include in the request.
 * @return The content of the request if there is one.
 * @throws Exception
 */
public static String net_httpclient_doAction(HTTP_METHOD method, String url, String jsonData,
        Map<String, String> headers) throws ConnectTimeoutException, SocketTimeoutException, Exception {
    String responseData = null;

    DefaultHttpClient httpclient = new DefaultHttpClient();

    // The time it takes to open TCP connection.
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_DEFAULT_TIMEOUT);
    // Timeout when server does not send data.
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
            CONNECTION_DEFAULT_DATA_RECEIVAL_TIMEOUT);
    // Some tuning that is not required for bit tests.
    //httpclient.getParams().setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    httpclient.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY, true);

    HttpRequestBase httpMethod = null;
    switch (method) {
    case POST:
        httpMethod = new HttpPost(url);
        //Add the body to the request.
        StringEntity se = new StringEntity(jsonData);
        ((HttpPost) httpMethod).setEntity(se);
        break;
    case DELETE:
        httpMethod = new HttpDelete(url);
        break;
    case GET:
        httpMethod = new HttpGet(url);
        break;
    }

    //Add the headers to the request.
    if (headers != null) {
        for (String header : headers.keySet()) {
            httpMethod.setHeader(header, headers.get(header));
        }
    }

    HttpResponse response = httpclient.execute(httpMethod);
    if (LOG_ENABLE) {
        Log.d(TAG,
                "HTTP OPERATION: Read from server - Status Code: " + response.getStatusLine().getStatusCode());
        Log.d(TAG, "HTTP OPERATION: Read from server - Status Message: "
                + response.getStatusLine().getReasonPhrase());
    }

    //Get the response body if there is one.
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        //responseData = EntityUtils.toString(entity, "UTF-8");

        InputStream instream = entity.getContent();
        responseData = IOUtils.convertStreamToString(instream);

        if (LOG_ENABLE)
            Log.i(TAG, "HTTP OPERATION: Read from server - return: " + responseData);
    }

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new Exception("Http operation " + method.name() + " failed with error code "
                + response.getStatusLine().getStatusCode() + "(" + response.getStatusLine().getReasonPhrase()
                + ")");
    }

    return responseData;
}

From source file:org.apache.maven.plugin.javadoc.JavadocUtil.java

/**
 * Creates a new {@code HttpClient} instance.
 *
 * @param settings The settings to use for setting up the client or {@code null}.
 * @param url The {@code URL} to use for setting up the client or {@code null}.
 *
 * @return A new {@code HttpClient} instance.
 *
 * @see #DEFAULT_TIMEOUT//w w  w  .  jav  a2  s.  co m
 * @since 2.8
 */
private static HttpClient createHttpClient(Settings settings, URL url) {
    DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
    httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_TIMEOUT);
    httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEFAULT_TIMEOUT);
    httpClient.getParams().setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // Some web servers don't allow the default user-agent sent by httpClient
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");

    if (settings != null && settings.getActiveProxy() != null) {
        Proxy activeProxy = settings.getActiveProxy();

        ProxyInfo proxyInfo = new ProxyInfo();
        proxyInfo.setNonProxyHosts(activeProxy.getNonProxyHosts());

        if (StringUtils.isNotEmpty(activeProxy.getHost())
                && (url == null || !ProxyUtils.validateNonProxyHosts(proxyInfo, url.getHost()))) {
            HttpHost proxy = new HttpHost(activeProxy.getHost(), activeProxy.getPort());
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (StringUtils.isNotEmpty(activeProxy.getUsername()) && activeProxy.getPassword() != null) {
                Credentials credentials = new UsernamePasswordCredentials(activeProxy.getUsername(),
                        activeProxy.getPassword());

                httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
            }
        }
    }

    return httpClient;
}

From source file:com.nextgis.maplibui.services.HTTPLoader.java

protected String signIn() throws IOException {
    //1. fix url//from www . j  a v  a 2 s  .  c  om
    String url;
    if (mUrl.startsWith("http"))
        url = mUrl + "/login";
    else
        url = "http://" + mUrl + "/login";

    HttpPost httppost = new HttpPost(url);
    List<NameValuePair> nameValuePairs = new ArrayList<>(2);
    nameValuePairs.add(new BasicNameValuePair("login", mLogin));
    nameValuePairs.add(new BasicNameValuePair("password", mPassword));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    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);

    HttpResponse response = httpclient.execute(httppost);
    //2 get cookie
    Header head = response.getFirstHeader("Set-Cookie");
    if (head == null)
        return null;
    return head.getValue();
}