Java Code Examples for org.apache.http.params.HttpConnectionParams#setSoTimeout()

The following examples show how to use org.apache.http.params.HttpConnectionParams#setSoTimeout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebServiceNtlmSender.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws ConfigurationException {
	super.configure();

	HttpParams httpParameters = new BasicHttpParams();
	HttpConnectionParams.setConnectionTimeout(httpParameters, getTimeout());
	HttpConnectionParams.setSoTimeout(httpParameters, getTimeout());
	httpClient = new DefaultHttpClient(connectionManager, httpParameters);
	httpClient.getAuthSchemes().register("NTLM", new NTLMSchemeFactory());
	CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
	httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new NTCredentials(cf.getUsername(), cf.getPassword(), Misc.getHostname(), getAuthDomain()));
	if (StringUtils.isNotEmpty(getProxyHost())) {
		HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
	}
}
 
Example 2
Source File: WebServiceUtil.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the one <code>WebServiceUtil</code> instance
 * @return the one <code>WebServiceUtil</code> instance
 */
public static WebServiceUtil getInstance() {
  // This needs to be here instead of in the constructor because
  // it uses classes that are in the AndroidSDK and thus would
  // cause Stub! errors when running the component descriptor.
  synchronized(httpClientSynchronizer) {
    if (httpClient == null) {
      SchemeRegistry schemeRegistry = new SchemeRegistry();
      schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
      BasicHttpParams params = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
      HttpConnectionParams.setSoTimeout(params, 20 * 1000);
      ConnManagerParams.setMaxTotalConnections(params, 20);
      ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params,
          schemeRegistry);
      WebServiceUtil.httpClient = new DefaultHttpClient(manager, params);
    }
  }
  return INSTANCE;
}
 
Example 3
Source File: HttpClientStack.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    // 创建一个 Apache HTTP 请求
    HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
    // 添加 performRequest 方法传入的 头信息
    addHeaders(httpRequest, additionalHeaders);
    // 添加 Volley 抽象请求了 Request 设置的 头信息
    addHeaders(httpRequest, request.getHeaders());
    // 回调( 如果被覆写的话 ) 预请求 方法
    onPrepareRequest(httpRequest);
    // 获取 Apache 请求的 HttpParams 对象
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();
    // TODO: Reevaluate this connection timeout based on more wide-scale
    // data collection and possibly different for wifi vs. 3G.
    // 设置超时时间
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    // 设置 SO_TIMEOUT
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    // 开始执行请求
    return mClient.execute(httpRequest);
}
 
Example 4
Source File: SOAPClient.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Sets up the client
 */
private void setup() {
    httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    HttpParams params = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
    httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
            return false;
        }
    });
}
 
Example 5
Source File: ClientBuilder.java    From hbc with Apache License 2.0 5 votes vote down vote up
public BasicClient build() {
  HttpParams params = new BasicHttpParams();
  if (proxyHost != null) {
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);
    params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
  }
  HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  HttpProtocolParams.setUserAgent(params, USER_AGENT);
  HttpConnectionParams.setSoTimeout(params, socketTimeoutMillis);
  HttpConnectionParams.setConnectionTimeout(params, connectionTimeoutMillis);
  return new BasicClient(name, hosts, endpoint, auth, enableGZip, processor, reconnectionManager,
          rateTracker, executorService, eventQueue, params, schemeRegistry);
}
 
Example 6
Source File: Connection.java    From DarkBot with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static ProxyClient createClient() {
	ProxyClient client = new ProxyClient();

	HttpConnectionParams.setConnectionTimeout(client.getParams(), 3000);
	HttpConnectionParams.setSoTimeout(client.getParams(), 3000);

	return client;
}
 
Example 7
Source File: HttpTaskFactory.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected HttpParams basicParams() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    // Make sure this connection will timeout
    HttpConnectionParams.setConnectionTimeout(params, 300000);
    HttpConnectionParams.setSoTimeout(params, 300000);
    return params;
}
 
Example 8
Source File: AsyncHttpClient.java    From Roid-Library with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the connection time oout. By default, 10 seconds
 * 
 * @param timeout the connect/socket timeout in milliseconds
 */
public void setTimeout(int timeout) {
    final HttpParams httpParams = this.httpClient.getParams();
    ConnManagerParams.setTimeout(httpParams, timeout);
    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
}
 
Example 9
Source File: DatabricksRestClientImpl425.java    From databricks-rest-client with Apache License 2.0 5 votes vote down vote up
protected void initClient(DatabricksServiceFactory.Builder builder) {
  try {

    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(null, null, new SecureRandom());

    SSLSocketFactory sf = new SSLSocketFactory(sslContext);
    Scheme httpsScheme = new Scheme("https", HTTPS_PORT, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, builder.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(params, builder.getSoTimeout());

    DefaultHttpClient defaultHttpClient = new DefaultHttpClient(cm, params);
    defaultHttpClient.setHttpRequestRetryHandler(retryHandler);

    // set authorization header if token base
    if (isNotEmpty(builder.getToken())) {
      isTokenAuth = true;
      authToken = builder.getToken();

    } else if (isNotEmpty(builder.getUsername()) && isNotEmpty(builder.getPassword())) {
      defaultHttpClient.getCredentialsProvider().setCredentials(
          new AuthScope(host, HTTPS_PORT),
          new UsernamePasswordCredentials(builder.getUsername(), builder.getPassword()));
    }

    client = new AutoRetryHttpClient(defaultHttpClient, retryStrategy);

  } catch (Exception e) {
    logger.error("", e);
  }

  url = String.format("https://%s/api/%s", host, apiVersion);
  mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
}
 
Example 10
Source File: SOAPClient.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for SOAPClient
 *
 * @param connectionTimeout connection time out in milliseconds
 * @param socketTimeout socket time out in milliseconds
 */
public SOAPClient(int connectionTimeout, int socketTimeout) {
    setup();
    HttpParams params = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, socketTimeout);
}
 
Example 11
Source File: HttpClientStack.java    From CrossBow with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    onPrepareRequest(httpRequest);
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();
    // TODO: Reevaluate this connection timeout based on more wide-scale
    // data collection and possibly different for wifi vs. 3G.
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    return mClient.execute(httpRequest);
}
 
Example 12
Source File: MultiController.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private boolean emailPassword(String password, String username, String email) {
    HttpClient client = new DefaultHttpClient();
    try {
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
        HttpConnectionParams.setSoTimeout(client.getParams(), 10000);
        HttpPost method = new HttpPost("http://subsonic.org/backend/sendMail.view");

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("from", "[email protected]"));
        params.add(new BasicNameValuePair("to", email));
        params.add(new BasicNameValuePair("subject", "Subsonic Password"));
        params.add(new BasicNameValuePair("text",
                "Hi there!\n\n" +
                        "You have requested to reset your Subsonic password.  Please find your new login details below.\n\n" +
                        "Username: " + username + "\n" +
                        "Password: " + password + "\n\n" +
                        "--\n" +
                        "The Subsonic Team\n" +
                        "subsonic.org"));
        method.setEntity(new UrlEncodedFormEntity(params, StringUtil.ENCODING_UTF8));
        client.execute(method);
        return true;
    } catch (Exception x) {
        LOG.warn("Failed to send email.", x);
        return false;
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example 13
Source File: AudioScrobblerService.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private String[] executeRequest(HttpUriRequest request) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 15000);

    try {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(request, responseHandler);
        return response.split("\\n");

    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example 14
Source File: AbstractWebIntegrationTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void createClient(String ctxPath) throws Exception {
  testProperties = new TestProperties();

  APP_BASE_PATH = testProperties.getApplicationPath("/" + ctxPath);
  LOGGER.info("Connecting to application "+APP_BASE_PATH);

  ClientConfig clientConfig = new DefaultApacheHttpClient4Config();
  clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
  client = ApacheHttpClient4.create(clientConfig);

  defaultHttpClient = (DefaultHttpClient) client.getClientHandler().getHttpClient();
  HttpParams params = defaultHttpClient.getParams();
  HttpConnectionParams.setConnectionTimeout(params, 3 * 60 * 1000);
  HttpConnectionParams.setSoTimeout(params, 10 * 60 * 1000);
}
 
Example 15
Source File: Executor.java    From blog with MIT License 5 votes vote down vote up
private static DefaultHttpClient initHttpClient()
{
	DefaultHttpClient httpClient = new DefaultHttpClient();
	HttpParams params = httpClient.getParams();
	HttpConnectionParams.setConnectionTimeout( params, connectionTimeoutMillis );
	HttpConnectionParams.setSoTimeout( params, socketTimeoutMillis );
	return httpClient;
}
 
Example 16
Source File: FetchCommentTask.java    From iZhihu with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected String doInBackground(Long... answerIds) {

    for (Long answerId : answerIds) {
        HttpGet httpGet = new HttpGet(getRequestUrl(answerId));
        httpGet.addHeader("User-Agent", USER_AGENT);
        httpGet.addHeader("Authorization", AUTHORIZATION);
        httpGet.addHeader("ZA", ZA);
        httpGet.addHeader("X-APP-VERSION", X_APP_VERSION);
        httpGet.addHeader("Cache-Control", "no-cache");

        try {
            DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
            HttpParams httpParams = defaultHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_SECONDS * 1000);
            HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SECONDS * 1000);

            HttpResponse httpResponse = defaultHttpClient.execute(httpGet);

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HTTP_STATUS_OK) {
                return EntityUtils.toString(httpResponse.getEntity());
            } else {
                throw new IOException(httpResponse.getStatusLine().getReasonPhrase());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return null;
}
 
Example 17
Source File: Utils.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public static HttpClient getClient() {
	if (client.get() == null) {
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, URL_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParams, URL_TIMEOUT);
		client.set(new DefaultHttpClient(httpParams));
	}
	return client.get();
}
 
Example 18
Source File: SimpleHttpClient.java    From product-ei with Apache License 2.0 5 votes vote down vote up
public SimpleHttpClient() {
    this.client = new DefaultHttpClient(new ThreadSafeClientConnManager());
    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);
    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
            return false;
        }
    });
}
 
Example 19
Source File: VersionService.java    From subsonic with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Resolves the latest available Subsonic version by screen-scraping a web page.
 *
 * @throws IOException If an I/O error occurs.
 */
private void readLatestVersion() throws IOException {

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 10000);
    HttpGet method = new HttpGet(VERSION_URL + "?v=" + getLocalVersion());
    String content;
    try {

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        content = client.execute(method, responseHandler);

    } finally {
        client.getConnectionManager().shutdown();
    }

    BufferedReader reader = new BufferedReader(new StringReader(content));
    Pattern finalPattern = Pattern.compile("SUBSONIC_FULL_VERSION_BEGIN(.*)SUBSONIC_FULL_VERSION_END");
    Pattern betaPattern = Pattern.compile("SUBSONIC_BETA_VERSION_BEGIN(.*)SUBSONIC_BETA_VERSION_END");

    try {
        String line = reader.readLine();
        while (line != null) {
            Matcher finalMatcher = finalPattern.matcher(line);
            if (finalMatcher.find()) {
                latestFinalVersion = new Version(finalMatcher.group(1));
                LOG.info("Resolved latest Subsonic final version to: " + latestFinalVersion);
            }
            Matcher betaMatcher = betaPattern.matcher(line);
            if (betaMatcher.find()) {
                latestBetaVersion = new Version(betaMatcher.group(1));
                LOG.info("Resolved latest Subsonic beta version to: " + latestBetaVersion);
            }
            line = reader.readLine();
        }

    } finally {
        reader.close();
    }
}
 
Example 20
Source File: TestHttpClient.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
protected HttpParams createHttpParams() {
    HttpParams params = super.createHttpParams();
    HttpConnectionParams.setSoTimeout(params, 30000);
    return params;
}