org.apache.http.params.CoreConnectionPNames Java Examples

The following examples show how to use org.apache.http.params.CoreConnectionPNames. 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: HttpUtil.java    From api-gateway-demo-sign-java with Apache License 2.0 8 votes vote down vote up
/**
 * HTTP PUT字节数组
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param bodys
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPut(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, byte[] bodys, List<String> signHeaderPrefixList, String appKey, String appSecret)
        throws Exception {
	headers = initialBasicHeader(HttpMethod.PUT, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);

	HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

    HttpPut put = new HttpPut(initUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
    	put.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    if (bodys != null) {
    	put.setEntity(new ByteArrayEntity(bodys));
    }

    return convert(httpClient.execute(put));
}
 
Example #2
Source File: StreamServerImpl.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
synchronized public void init(InetAddress bindAddress, Router router) throws InitializationException {

        try {

            this.router = router;

            this.serverSocket =
                    new ServerSocket(
                            configuration.getListenPort(),
                            configuration.getTcpConnectionBacklog(),
                            bindAddress
                    );

            log.info("Created socket (for receiving TCP streams) on: " + serverSocket.getLocalSocketAddress());

            this.globalParams
                    .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, configuration.getDataWaitTimeoutSeconds() * 1000)
                    .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, configuration.getBufferSizeKilobytes() * 1024)
                    .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, configuration.isStaleConnectionCheck())
                    .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, configuration.isTcpNoDelay());

        } catch (Exception ex) {
            throw new InitializationException("Could not initialize "+getClass().getSimpleName()+": " + ex.toString(), ex);
        }

    }
 
Example #3
Source File: HttpMethed.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * constructor.
 */
public static HttpResponse getSignWeight(String httpNode, String transactionSignString) {
    try {
        String requestUrl = "http://" + httpNode + "/wallet/getsignweight";
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                connectionTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
        httppost = new HttpPost(requestUrl);
        httppost.setHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Connection", "Close");
        if (transactionSignString != null) {
            StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httppost.setEntity(entity);
        }
        response = httpClient.execute(httppost);
    } catch (Exception e) {
        e.printStackTrace();
        httppost.releaseConnection();
        return null;
    }
    //httppost.releaseConnection();
    return response;
}
 
Example #4
Source File: HttpMethed.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * constructor.
 */
public static HttpResponse getTransactionApprovedList(String httpNode,
                                                      String transactionSignString) {
    try {
        String requestUrl = "http://" + httpNode + "/wallet/getapprovedlist";
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                connectionTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
        httppost = new HttpPost(requestUrl);
        httppost.setHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Connection", "Close");
        if (transactionSignString != null) {
            StringEntity entity = new StringEntity(transactionSignString, Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httppost.setEntity(entity);
        }
        response = httpClient.execute(httppost);
    } catch (Exception e) {
        e.printStackTrace();
        httppost.releaseConnection();
        return null;
    }
    //httppost.releaseConnection();
    return response;
}
 
Example #5
Source File: HttpMethed.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * constructor.
 */
public static HttpResponse createConnect(String url, JsonObject requestBody) {
    try {
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                connectionTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
        httppost = new HttpPost(url);
        httppost.setHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Connection", "Close");
        if (requestBody != null) {
            StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httppost.setEntity(entity);
        }
        response = httpClient.execute(httppost);
    } catch (Exception e) {
        e.printStackTrace();
        httppost.releaseConnection();
        return null;
    }
    return response;
}
 
Example #6
Source File: HttpMethed.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * constructor.
 */
public static HttpResponse createConnect1(String url, JSONObject requestBody) {
    try {
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                connectionTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                connectionTimeout * 10000);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout * 10000);
        httppost = new HttpPost(url);
        httppost.setHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Connection", "Close");
        if (requestBody != null) {
            StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httppost.setEntity(entity);
        }
        response = httpClient.execute(httppost);
    } catch (Exception e) {
        e.printStackTrace();
        httppost.releaseConnection();
        return null;
    }
    return response;
}
 
Example #7
Source File: StreamServerImpl.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
synchronized public void init(InetAddress bindAddress, Router router) throws InitializationException {

        try {

            this.router = router;

            this.serverSocket =
                    new ServerSocket(
                            configuration.getListenPort(),
                            configuration.getTcpConnectionBacklog(),
                            bindAddress
                    );

            log.info("Created socket (for receiving TCP streams) on: " + serverSocket.getLocalSocketAddress());

            this.globalParams
                    .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, configuration.getDataWaitTimeoutSeconds() * 1000)
                    .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, configuration.getBufferSizeKilobytes() * 1024)
                    .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, configuration.isStaleConnectionCheck())
                    .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, configuration.isTcpNoDelay());

        } catch (Exception ex) {
            throw new InitializationException("Could not initialize "+getClass().getSimpleName()+": " + ex.toString(), ex);
        }

    }
 
Example #8
Source File: IncompletePostTestCase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testIncompleteWrite() throws Exception {
    PostEndpoint.invoked = false;

    //make sure incomplete writes do not block threads
    //and that incoplete data is not delivered to the endpoint
    for (int i = 0; i < 1000; ++i) {
        Socket socket = new Socket(url.getHost(), url.getPort());
        socket.getOutputStream().write(
                "POST /post HTTP/1.1\r\nHost: localhost\r\nContent-length:10\r\n\r\ntest".getBytes(StandardCharsets.UTF_8));
        socket.getOutputStream().flush();
        socket.getOutputStream().close();
        socket.close();
    }

    Assertions.assertFalse(PostEndpoint.invoked);
    RestAssuredConfig config = RestAssured.config()
            .httpClient(HttpClientConfig.httpClientConfig()
                    .setParam(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000)
                    .setParam(CoreConnectionPNames.SO_TIMEOUT, 1000));

    RestAssured.given().config(config).get("/post").then().body(Matchers.is("ok"));
}
 
Example #9
Source File: Axis2ServerExtension.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public void onExecutionStart() throws AutomationFrameworkException {
    serverManager = new Axis2ServerManager();
    //To set the socket can be bound even though a previous connection is still in a timeout state.
    if (System.getProperty(CoreConnectionPNames.SO_REUSEADDR) == null) {
        System.setProperty(CoreConnectionPNames.SO_REUSEADDR, "true");
    }
    try {
        serverManager.start();
        log.info(".................Deploying services..............");
        serverManager.deployService(ServiceNameConstants.LB_SERVICE_1);
        serverManager.deployService(ServiceNameConstants.SIMPLE_STOCK_QUOTE_SERVICE);
        serverManager.deployService(ServiceNameConstants.SECURE_STOCK_QUOTE_SERVICE);
        serverManager.deployService(ServiceNameConstants.SIMPLE_AXIS2_SERVICE);
    } catch (IOException e) {
        handleException("Error While Deploying services", e);
    }
}
 
Example #10
Source File: SampleAxis2Server.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
public void start() throws IOException {
    log.info("Starting sample Axis2 server");
    //To set the socket can be bound even though a previous connection is still in a timeout state.
    if (System.getProperty(CoreConnectionPNames.SO_REUSEADDR) == null) {
        System.setProperty(CoreConnectionPNames.SO_REUSEADDR, "true");
    }
    listenerManager = new ListenerManager();
    listenerManager.init(cfgCtx);
    listenerManager.start();
    try {
        Thread.sleep(2000);
    } catch (InterruptedException ignored) {

    }
    started = true;
}
 
Example #11
Source File: GetClient.java    From javabase with Apache License 2.0 6 votes vote down vote up
public void get() throws IOException {
    String requesturl = "http://www.tuling123.com/openapi/api";
    // 声明httpclient 每一个会话有一个独立的httpclient
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    StringBuilder params = new StringBuilder();
    params.append(requesturl + "?");
    params.append("key=" + URLEncoder.encode("4b441cb500f431adc6cc0cb650b4a5d0", REQUEST_CHARSET)).append("&");
    params.append("info=" + URLEncoder.encode("4b441cb500f431adc6cc0cb650b4a5d0", REQUEST_CHARSET));
    try {
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); // 请求超时
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); // 读取超时
        HttpGet httpGet = new HttpGet(params.toString());
        response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String content = EntityUtils.toString(entity, "utf-8");
        log.info(content);
        EntityUtils.consume(entity);
    } catch (Exception e) {
        log.error("" + e);
    } finally {
        if (response != null)
            response.close();
    }
}
 
Example #12
Source File: TestHttpClientGet.java    From AthenaServing with Apache License 2.0 6 votes vote down vote up
public static String getRequestFromCompansion(String url){
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
    HttpGet get = new HttpGet(url);
    try{
        // 发送GET请求
        HttpResponse httpResponse = httpClient.execute(get);
        // 如果服务器成功地返回响应
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
        {
            // 获取服务器响应字符串
            String result = EntityUtils.toString(httpResponse.getEntity());
            return result;
        } else {
            // 如果服务器失败返回响应数据"error"
            return "error";
        }
    }catch(Exception e){
        // 捕获超时异常 并反馈给调用者
        e.printStackTrace();
        return "connection time out";
    }finally{
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example #13
Source File: HttpUtil.java    From api-gateway-demo-sign-java with Apache License 2.0 6 votes vote down vote up
/**
 * HTTP GET
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpGet(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, List<String> signHeaderPrefixList, String appKey, String appSecret)
        throws Exception {
    headers = initialBasicHeader(HttpMethod.GET, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);

    HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

    HttpGet get = new HttpGet(initUrl(host, path, querys));

    for (Map.Entry<String, String> e : headers.entrySet()) {
        get.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    return convert(httpClient.execute(get));
}
 
Example #14
Source File: HttpUtil.java    From api-gateway-demo-sign-java with Apache License 2.0 6 votes vote down vote up
/**
 * HTTP POST表单
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param bodys
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys, List<String> signHeaderPrefixList, String appKey, String appSecret)
        throws Exception {
    if (headers == null) {
        headers = new HashMap<String, String>();
    }

    headers.put(HttpHeader.HTTP_HEADER_CONTENT_TYPE, ContentType.CONTENT_TYPE_FORM);

    headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, bodys, signHeaderPrefixList, appKey, appSecret);

    HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

    HttpPost post = new HttpPost(initUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    UrlEncodedFormEntity formEntity = buildFormEntity(bodys);
    if (formEntity != null) {
        post.setEntity(formEntity);
    }

    return convert(httpClient.execute(post));
}
 
Example #15
Source File: Axis2ServerExtension.java    From product-ei with Apache License 2.0 6 votes vote down vote up
public void onExecutionStart() throws AutomationFrameworkException {
    serverManager = new Axis2ServerManager();
    //To set the socket can be bound even though a previous connection is still in a timeout state.
    if (System.getProperty(CoreConnectionPNames.SO_REUSEADDR) == null) {
        System.setProperty(CoreConnectionPNames.SO_REUSEADDR, "true");
    }
    try {
        serverManager.start();
        log.info(".................Deploying services..............");
        serverManager.deployService(ServiceNameConstants.LB_SERVICE_1);
        serverManager.deployService(ServiceNameConstants.SIMPLE_STOCK_QUOTE_SERVICE);
        serverManager.deployService(ServiceNameConstants.SECURE_STOCK_QUOTE_SERVICE);
        serverManager.deployService(ServiceNameConstants.SIMPLE_AXIS2_SERVICE);
    } catch (IOException e) {
        handleException("Error While Deploying services", e);
    }
}
 
Example #16
Source File: SampleAxis2Server.java    From product-ei with Apache License 2.0 6 votes vote down vote up
public void start() throws IOException {
    log.info("Starting sample Axis2 server");
    //To set the socket can be bound even though a previous connection is still in a timeout state.
    if (System.getProperty(CoreConnectionPNames.SO_REUSEADDR) == null) {
        System.setProperty(CoreConnectionPNames.SO_REUSEADDR, "true");
    }
    listenerManager = new ListenerManager();
    listenerManager.init(cfgCtx);
    listenerManager.start();
    try {
        Thread.sleep(2000);
    } catch (InterruptedException ignored) {

    }
    started = true;
}
 
Example #17
Source File: HttpUtil.java    From api-gateway-demo-sign-java with Apache License 2.0 6 votes vote down vote up
/**
 * HTTP PUT 字符串
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param body
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPut(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, String body, List<String> signHeaderPrefixList, String appKey, String appSecret)
        throws Exception {
	headers = initialBasicHeader(HttpMethod.PUT, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);

	HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

    HttpPut put = new HttpPut(initUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        put.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    if (StringUtils.isNotBlank(body)) {
        put.setEntity(new StringEntity(body, Constants.ENCODING));

    }

    return convert(httpClient.execute(put));
}
 
Example #18
Source File: GetClient.java    From javabase with Apache License 2.0 6 votes vote down vote up
/**
 * 此处解释下MaxtTotal和DefaultMaxPerRoute的区别:
 * 1、MaxtTotal是整个池子的大小;
 * 2、DefaultMaxPerRoute是根据连接到的主机对MaxTotal的一个细分;比如:
 * MaxtTotal=400 DefaultMaxPerRoute=200
 * 而我只连接到http://sishuok.com时,到这个主机的并发最多只有200;而不是400;
 * 而我连接到http://sishuok.com 和 http://qq.com时,到每个主机的并发最多只有200;即加起来是400(但不能超过400);所以起作用的设置是DefaultMaxPerRoute。
 */
public HttpParams getHttpParams() {
    HttpParams params = new BasicHttpParams();
    // 设置连接超时时间
    Integer CONNECTION_TIMEOUT = 2 * 1000; // 设置请求超时2秒钟 根据业务调整
    Integer SO_TIMEOUT = 2 * 1000; // 设置等待数据超时时间2秒钟 根据业务调整
    // 定义了当从ClientConnectionManager中检索ManagedClientConnection实例时使用的毫秒级的超时时间
    // 这个参数期望得到一个java.lang.Long类型的值。如果这个参数没有被设置,默认等于CONNECTION_TIMEOUT,因此一定要设置
    Long CONN_MANAGER_TIMEOUT = 500L; // 该值就是连接不够用的时候等待超时时间,一定要设置,而且不能太大 ()

    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
    params.setLongParameter(ClientPNames.CONN_MANAGER_TIMEOUT, CONN_MANAGER_TIMEOUT);
    // 在提交请求之前 测试连接是否可用
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
    return params;
}
 
Example #19
Source File: HttpUtil.java    From api-gateway-demo-sign-java with Apache License 2.0 6 votes vote down vote up
/**
 * HTTP POST 字节数组
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param bodys
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, byte[] bodys, List<String> signHeaderPrefixList, String appKey, String appSecret)
        throws Exception {
	headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);

	HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

    HttpPost post = new HttpPost(initUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    if (bodys != null) {
        post.setEntity(new ByteArrayEntity(bodys));
    }

    return convert(httpClient.execute(post));
}
 
Example #20
Source File: HttpUtil.java    From api-gateway-demo-sign-java with Apache License 2.0 6 votes vote down vote up
/**
 * Http POST 字符串
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param body
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, String body, List<String> signHeaderPrefixList, String appKey, String appSecret)
        throws Exception {
	headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);

	HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

    HttpPost post = new HttpPost(initUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    if (StringUtils.isNotBlank(body)) {
        post.setEntity(new StringEntity(body, Constants.ENCODING));

    }

    return convert(httpClient.execute(post));
}
 
Example #21
Source File: THttpClient.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
public void setConnectTimeout(int timeout) {
  connectTimeout_ = timeout;
  if (null != this.client) {
    // WARNING, this modifies the HttpClient params, this might have an impact elsewhere if the
    // same HttpClient is used for something else.
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout_);
  }
}
 
Example #22
Source File: GalaxyHttpClient.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
public GalaxyHttpClient setConnectTimeout(int timeout) {
  connectTimeout_ = timeout;
  if (null != this.client) {
    // WARNING, this modifies the HttpClient params, this might have an impact elsewhere if the
    // same HttpClient is used for something else.
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout_);
  }
  return this;
}
 
Example #23
Source File: TalosHttpClient.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
public TalosHttpClient setConnectTimeout(int timeout) {
  connectTimeout_ = timeout;
  if (null != this.client) {
    // WARNING, this modifies the HttpClient params, this might have an impact elsewhere if the
    // same HttpClient is used for something else.
    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout_);
  }
  return this;
}
 
Example #24
Source File: THttpClient.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
public void setReadTimeout(int timeout) {
  readTimeout_ = timeout;
  if (null != this.client) {
    // WARNING, this modifies the HttpClient params, this might have an impact elsewhere if the
    // same HttpClient is used for something else.
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout_);
  }
}
 
Example #25
Source File: TelephonyActivity.java    From nearbydemo with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void onPreExecute() {
	super.onPreExecute();
	mClient = new DefaultHttpClient();
	mClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
	mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 15000);
}
 
Example #26
Source File: ApiServer.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public ListenerThread(final ApiServer requestHandler, final int port) {
    try {
        _serverSocket = new ServerSocket(port);
    } catch (final IOException ioex) {
        s_logger.error("error initializing api server", ioex);
        return;
    }

    _params = new BasicHttpParams();
    _params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
    .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
    .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
    .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
    .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

    // Set up the HTTP protocol processor
    final BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    // Set up request handlers
    final HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
    reqistry.register("*", requestHandler);

    // Set up the HTTP service
    _httpService = new HttpService(httpproc, new NoConnectionReuseStrategy(), new DefaultHttpResponseFactory());
    _httpService.setParams(_params);
    _httpService.setHandlerResolver(reqistry);
}
 
Example #27
Source File: HttpsUtils.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public static HttpClient getNewHttpClient() {
	try {

		KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
		trustStore.load(null, null);
		SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
		sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		HttpParams params = new BasicHttpParams();

		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		HttpProtocolParams.setUserAgent(params, HttpHeader.getUA());
		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		registry.register(new Scheme("https", sf, 443));

		ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
		DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);

		httpClient.setCookieStore(new BasicCookieStore());

		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 25000);
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 25000);
		return httpClient;
	} catch (Exception e) {
		return new DefaultHttpClient();
	}
}
 
Example #28
Source File: Client.java    From hbase with Apache License 2.0 5 votes vote down vote up
private void initialize(Cluster cluster, boolean sslEnabled) {
  this.cluster = cluster;
  this.sslEnabled = sslEnabled;
  extraHeaders = new ConcurrentHashMap<>();
  String clspath = System.getProperty("java.class.path");
  LOG.debug("classpath " + clspath);
  this.httpClient = new DefaultHttpClient();
  this.httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
}
 
Example #29
Source File: MetricsHttpClient.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
public MetricsHttpClient setSocketTimeout(int timeout) {
  socketTimeout_ = timeout;
  if (null != this.client) {
    // WARNING, this modifies the HttpClient params, this might have an impact elsewhere if the
    // same HttpClient is used for something else.
    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout_);
  }
  return this;
}
 
Example #30
Source File: HttpUtil.java    From AthenaServing with Apache License 2.0 5 votes vote down vote up
public static String myHttpGet(String url){
    HttpClient httpClient = new DefaultHttpClient();
    //设置超时时间
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);
    HttpGet get = new HttpGet(url);
    try{
        // 发送GET请求
        HttpResponse httpResponse = httpClient.execute(get);
        // 如果服务器成功地返回响应
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
        {
            // 获取服务器响应字符串
            String result = EntityUtils.toString(httpResponse.getEntity());
            return result;
        } else {
            // 如果服务器失败返回响应数据"error"
            return "error";
        }
    }catch(Exception e){
        // 捕获超时异常 并反馈给调用者
        e.printStackTrace();
        return "connection time out";
    }finally{
        httpClient.getConnectionManager().shutdown();
    }
}