public void initSubtitleResource(final String url) { new Thread(new Runnable() { @Override public void run() { try { HttpClient client = new DefaultHttpClient(); client.getParams().setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); HttpGet httpGet = new HttpGet(url); HttpResponse response = client.execute(httpGet); HttpEntity entity = response.getEntity(); String results = EntityUtils.toString(entity, "utf-8"); parseSubtitleStr(results); } catch (Exception e) { Log.e("CCVideoViewDemo", "" + e.getMessage()); } } }).start(); }
public boolean testConnection() throws ConnectionTestException { // store the old timeouts Integer oldTimeout = getIntClientParameter(CoreConnectionPNames.CONNECTION_TIMEOUT); Integer oldSocketTimeout = getIntClientParameter(CoreConnectionPNames.SO_TIMEOUT); boolean isValid = false; try { int tempTime = HCPMoverProperties.CONNECTION_TEST_TIMEOUT_OVERRIDE_MS.getAsInt(); setIntClientParameter(tempTime, CoreConnectionPNames.CONNECTION_TIMEOUT); setIntClientParameter(tempTime, CoreConnectionPNames.SO_TIMEOUT); isValid = doTestConnection(); } finally { // restore the old timeouts setIntClientParameter(oldTimeout, CoreConnectionPNames.CONNECTION_TIMEOUT); setIntClientParameter(oldSocketTimeout, CoreConnectionPNames.SO_TIMEOUT); } return isValid; }
/** * Initializes this session input buffer. * * @param instream the source input stream. * @param buffersize the size of the internal buffer. * @param params HTTP parameters. */ protected void init(final InputStream instream, int buffersize, final HttpParams params) { if (instream == null) { throw new IllegalArgumentException("Input stream may not be null"); } if (buffersize <= 0) { throw new IllegalArgumentException("Buffer size may not be negative or zero"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.instream = instream; this.buffer = new byte[buffersize]; this.bufferpos = 0; this.bufferlen = 0; this.linebuffer = new ByteArrayBuffer(buffersize); this.charset = Charset.forName(HttpProtocolParams.getHttpElementCharset(params)); this.ascii = this.charset.equals(ASCII); this.decoder = null; this.maxLineLen = params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1); this.minChunkLimit = params.getIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 512); this.metrics = createTransportMetrics(); this.onMalformedInputAction = HttpProtocolParams.getMalformedInputAction(params); this.onUnMappableInputAction = HttpProtocolParams.getUnmappableInputAction(params); }
/** * Initializes this session output buffer. * * @param outstream the destination output stream. * @param buffersize the size of the internal buffer. * @param params HTTP parameters. */ protected void init(final OutputStream outstream, int buffersize, final HttpParams params) { if (outstream == null) { throw new IllegalArgumentException("Input stream may not be null"); } if (buffersize <= 0) { throw new IllegalArgumentException("Buffer size may not be negative or zero"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.outstream = outstream; this.buffer = new ByteArrayBuffer(buffersize); this.charset = Charset.forName(HttpProtocolParams.getHttpElementCharset(params)); this.ascii = this.charset.equals(ASCII); this.encoder = null; this.minChunkLimit = params.getIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 512); this.metrics = createTransportMetrics(); this.onMalformedInputAction = HttpProtocolParams.getMalformedInputAction(params); this.onUnMappableInputAction = HttpProtocolParams.getUnmappableInputAction(params); }
/** * Creates an instance of this class. * * @param buffer the session input buffer. * @param parser the line parser. * @param params HTTP parameters. */ public AbstractMessageParser( final SessionInputBuffer buffer, final LineParser parser, final HttpParams params) { super(); if (buffer == null) { throw new IllegalArgumentException("Session input buffer may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.sessionBuffer = buffer; this.maxHeaderCount = params.getIntParameter( CoreConnectionPNames.MAX_HEADER_COUNT, -1); this.maxLineLen = params.getIntParameter( CoreConnectionPNames.MAX_LINE_LENGTH, -1); this.lineParser = (parser != null) ? parser : BasicLineParser.DEFAULT; this.headerLines = new ArrayList<CharArrayBuffer>(); this.state = HEAD_LINE; }
/** * 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)); }
/** * 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)); }
/** * 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)); }
/** * 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)); }
/** * 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)); }
/** * 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)); }
private QSystemHtmlInstance() { this.params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000). setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024). setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false). setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true). setParameter(CoreProtocolPNames.ORIGIN_SERVER, "QSystemReportHttpServer/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("*", new HttpQSystemReportsHandler()); // Set up the HTTP service this.httpService = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params); }
public static String postUrl(String url, String body) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8"); //请求超时 ,连接超时 httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT); //读取超时 httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT); try { StringEntity entity = new StringEntity(body, "UTF-8"); httppost.setEntity(entity); System.out.println(entity.toString()); HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String charsetName = EntityUtils.getContentCharSet(response.getEntity()); //System.out.println(charsetName + "<<<<<<<<<<<<<<<<<"); String rs = EntityUtils.toString(response.getEntity()); //System.out.println( ">>>>>>" + rs); return rs; } else { //System.out.println("Eorr occus"); } } catch (Exception e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } return ""; }
public RequestListenerThread(Context context) throws IOException, BindException { serversocket = new ServerSocket(PORT); params = new BasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000).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 BasicHttpProcessor httpProcessor = new BasicHttpProcessor(); httpProcessor.addInterceptor(new ResponseDate()); httpProcessor.addInterceptor(new ResponseServer()); httpProcessor.addInterceptor(new ResponseContent()); httpProcessor.addInterceptor(new ResponseConnControl()); // Set up the HTTP service this.httpService = new YaaccHttpService(httpProcessor, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), context); }
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(); } }
/** * 此处解释下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; }
/** * 微信自定义信任管理器X509TrustManager * @param httpclient * @return */ private static HttpClient initHttpClient(HttpClient httpclient) { try { TrustManager[] tm = { new MyX509TrustManager() }; // 取得SSL的SSLContext实例 SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); // 初始化SSLContext sslContext.init(null, tm, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 SocketFactory ssf = (SocketFactory) sslContext.getSocketFactory(); ClientConnectionManager ccm = new DefaultHttpClient().getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 8443)); HttpParams params = new BasicHttpParams(); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000); httpclient = new DefaultHttpClient(ccm, params); } catch (Exception ex) { Exceptions.printException(ex); } return httpclient; }
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; }
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); } }
/** * * ʹ��HttpClient����һ��get��ʽ�ij���������. * * @param urlpath * @return * @author shimiso * @update 2012-6-29 ����11:58:14 */ public static HttpResponse sendHttpGet(String urlpath) { HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet(urlpath); httpclient.getParams().setParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, 20000); // ��������ʱʱ�� httpclient.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, 20000); // ��ȡ��ʱ HttpResponse response = httpclient.execute(httpget); return response; } catch (Exception e) { e.printStackTrace(); } return null; }
public RequestListenerThread(int port, final String docroot) throws IOException { this.serversocket = new ServerSocket(port); this.params = new SyncBasicHttpParams(); this.params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000).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 HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[]{ new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); // Set up request handlers HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("*", new HttpFileHandler()); // Set up the HTTP service this.httpService = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params); }
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); } }
private HttpServer(WifiManager wifiManager) { this.wifiManager = wifiManager; this.listenPort = 0; this.handlerRegistry = new HttpRequestHandlerRegistry(); this.params = new BasicHttpParams(); this.params .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "4thLineAndroidHttpServer/1.0") .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter( CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); startServer(); }
/** * post access to the network, you need to use in the sub-thread * * @param url url * @param params params * @return response inputStream * @throws IOException In the case of non-200 status code is returned, it would have thrown */ public static InputStream postInputStream(String url, Map<String, String> params) throws IOException { List<NameValuePair> list = new ArrayList<NameValuePair>(); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry .getValue())); } } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entity); org.apache.http.client.HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Constant.TimeInApplication.NET_TIMEOUT); client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, Constant.TimeInApplication.NET_TIMEOUT); HttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { return response.getEntity().getContent(); } else { throw new IllegalArgumentException("postInputStreamInSubThread response status code is " + response.getStatusLine().getStatusCode()); } }
/** * Send get to URL. * * @param url * @return */ public static String sendGet(String url) { HttpClient httpClient = new DefaultHttpClient(); String content = null; try { if(url.indexOf("https") != -1){ httpClient = wrapClient(httpClient); } HttpGet httpGet = new HttpGet(url); // 请求超时 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 40000); // 读取超时 httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 40000); httpClient.getParams().setParameter(AllClientPNames.STRICT_TRANSFER_ENCODING,"GBK"); content = httpClient.execute(httpGet, new BasicResponseHandler()); } catch (Exception e) { log.error("Get url faild, url: " + url, e); content = null; } finally { httpClient.getConnectionManager().shutdown(); } return content; }
/** * Create an unauthenticated Jenkins HTTP client * * @param uri * Location of the jenkins server (ex. http://localhost:8080) */ public JenkinsHttpClient(URI uri) { this.context = uri.getPath(); if (!context.endsWith("/")) { context += "/"; } this.uri = uri; this.mapper = getDefaultMapper(); HttpParams httpParams = new BasicHttpParams(); httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT_IN_MILLISECONDS); httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT_IN_MILLISECONDS); this.client = new DefaultHttpClient(httpParams); this.httpResponseValidator = new HttpResponseValidator(); this.contentExtractor = new HttpResponseContentExtractor(); }
private void createClient() { BasicHttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeoutMs); httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeoutMs); HttpClientParams.setRedirecting(httpParams, allowRedirects); HttpClientParams.setConnectionManagerTimeout(httpParams, connectionManagerTimeoutMs); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry); connectionManager.setMaxTotal(maxConnections); connectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams); this.client = new HttpClient4Client(httpClient); }
public static String getExternalIP() { String extIP = ""; HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 2000); httpclient.getParams().setIntParameter( CoreConnectionPNames.CONNECTION_TIMEOUT, 2000); try { HttpGet httpget = new HttpGet(Constants.URL_GET_EXTERNAL_ADDR); HttpResponse response; response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { extIP = EntityUtils.toString(entity); } } catch (IOException e) { if (Constants.ENABLE_LOGGING) { e.printStackTrace(); } } finally { httpclient.getConnectionManager().shutdown(); } return (extIP == "" ? "" : extIP.replace("\n", "")); }