@Override public CloseableHttpAsyncClient generateClient () { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope (AuthScope.ANY), new UsernamePasswordCredentials(serviceUser, servicePass)); RequestConfig rqconf = RequestConfig.custom() .setCookieSpec(CookieSpecs.DEFAULT) .setSocketTimeout(Timeouts.SOCKET_TIMEOUT) .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT) .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT) .build(); CloseableHttpAsyncClient res = HttpAsyncClients.custom () .setDefaultCredentialsProvider (credsProvider) .setDefaultRequestConfig(rqconf) .build (); res.start (); return res; }
/** * Builds a custom Http client with custom DNS resolution, disabling persistent cookie stores and with custom * timeout values. * * @return An http client to be used to execute test requests to nginx. */ static CloseableHttpClient buildHttpClient() { return HttpClients.custom() .setConnectionManager(buildConnectionManager()) .setDefaultRequestConfig(RequestConfig.custom() // Waiting for a connection from connection manager .setConnectionRequestTimeout(100) // Waiting for connection to establish .setConnectTimeout(100) .setExpectContinueEnabled(false) // Waiting for data .setSocketTimeout(200) // Do not allow cookies to be stored between calls. .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .build()) .setRetryHandler(buildRetryHandler()) .disableRedirectHandling().build(); }
@Override public CloseableHttpAsyncClient generateClient () { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope (AuthScope.ANY), new UsernamePasswordCredentials(username, password)); RequestConfig rqconf = RequestConfig.custom() .setCookieSpec(CookieSpecs.DEFAULT) .setSocketTimeout(Timeouts.SOCKET_TIMEOUT) .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT) .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT) .build(); CloseableHttpAsyncClient res = HttpAsyncClients.custom () .setDefaultCredentialsProvider (credsProvider) .setDefaultRequestConfig(rqconf) .build (); res.start (); return res; }
private HttpRequestBase apiRequest(String apiMethod, List<NameValuePair> params) { HttpPost post = new HttpPost(getRestApiUrl(apiMethod)); post.setConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build()); List<NameValuePair> formFields = new ArrayList<>(); formFields.add(new BasicNameValuePair("api.token", myPassword)); formFields.addAll(params); try { post.setEntity(new UrlEncodedFormEntity(formFields, "UTF-8")); } catch (UnsupportedEncodingException ignored) { // cannot happen } return post; }
@Override protected CloseableHttpResponse send(CloseableHttpClient httpClient, String base) throws Exception { List<NameValuePair> formParams = new ArrayList<>(); for (String key : params.keySet()) { String value = params.get(key); formParams.add(new BasicNameValuePair(key, value)); } HttpPost request = new HttpPost(base); RequestConfig localConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.STANDARD) .build(); request.setConfig(localConfig); request.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8")); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); //内容为post return httpClient.execute(request); }
private HttpUtils(HttpRequestBase request) { this.request = request; this.clientBuilder = HttpClientBuilder.create(); this.isHttps = request.getURI().getScheme().equalsIgnoreCase("https"); this.config = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY); this.cookieStore = new BasicCookieStore(); if (request instanceof HttpPost) { this.type = 1; this.builder = EntityBuilder.create().setParameters(new ArrayList<NameValuePair>()); } else if (request instanceof HttpGet) { this.type = 2; this.uriBuilder = new URIBuilder(); } else if (request instanceof HttpPut) { this.type = 3; this.builder = EntityBuilder.create().setParameters(new ArrayList<NameValuePair>()); } else if (request instanceof HttpDelete) { this.type = 4; this.uriBuilder = new URIBuilder(); } }
public HttpUriRequest toHttpUriRequest() { LOGGER.debug("in createRequestBuilder"); RequestBuilder requestBuilder = createRequestBuilder(); int timeout = httpServiceInfo.getTimeout(); RequestConfig.Builder requestConfigBuilder = RequestConfig.custom() .setConnectionRequestTimeout(timeout) .setSocketTimeout(timeout) .setConnectTimeout(timeout) .setCookieSpec(CookieSpecs.IGNORE_COOKIES); requestBuilder.setConfig(requestConfigBuilder.build()); if (StringUtils.isNoneEmpty(httpServiceInfo.getContentType())) { requestBuilder.addHeader("Content-Type", httpServiceInfo.getContentType()); } else { requestBuilder.addHeader("Content-Type", httpServletRequest.getContentType()); } return requestBuilder.build(); }
private static HttpUriRequest post0(String url, Map<String, String> params) { RequestBuilder requestBuilder = RequestBuilder.post().setCharset(CHARSET).setUri(url); RequestConfig.Builder requestConfigBuilder = RequestConfig.custom() .setConnectionRequestTimeout(TIMEOUT) .setSocketTimeout(TIMEOUT) .setConnectTimeout(TIMEOUT).setCookieSpec(CookieSpecs.IGNORE_COOKIES); requestBuilder.setConfig(requestConfigBuilder.build()); if (params != null && params.size() > 0) { List<NameValuePair> nvList = new ArrayList<>(); for (Map.Entry<String, String> param : params.entrySet()) { Object value = param.getValue(); if (value == null) { continue; } nvList.add(new BasicNameValuePair(param.getKey(), value.toString())); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvList, CHARSET); requestBuilder.setEntity(formEntity); } requestBuilder.addHeader("Connection", "Keep-Alive"); return requestBuilder.build(); }
public HttpTransportClient(int retryAttemptsNetworkErrorCount, int retryAttemptsInvalidStatusCount) { this.retryAttemptsNetworkErrorCount = retryAttemptsNetworkErrorCount; this.retryAttemptsInvalidStatusCount = retryAttemptsInvalidStatusCount; CookieStore cookieStore = new BasicCookieStore(); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(SOCKET_TIMEOUT_MS) .setConnectTimeout(CONNECTION_TIMEOUT_MS) .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS) .setCookieSpec(CookieSpecs.STANDARD) .build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(MAX_SIMULTANEOUS_CONNECTIONS); connectionManager.setDefaultMaxPerRoute(MAX_SIMULTANEOUS_CONNECTIONS); httpClient = HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .setDefaultCookieStore(cookieStore) .setUserAgent(USER_AGENT) .build(); }
public NestSession(String username, String password) throws LoginException { super(); theLine = null; theBody = null; response = null; theUsername = new String(username); thePassword = new String(password); log.info("Starting Nest login..."); retry = 0; // Trust own CA and all self-signed certs sslcontext = SSLContexts.createDefault(); // Allow TLSv1 protocol only sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); globalConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.STANDARD) .build(); _login(); }
@Override protected CloseableHttpResponse send(CloseableHttpClient httpClient, String base) throws Exception { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { String value = params.get(key); formparams.add(new BasicNameValuePair(key, value)); } HttpPost request = new HttpPost(base); RequestConfig localConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.STANDARD) .build(); request.setConfig(localConfig); request.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8")); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); //内容为post return httpClient.execute(request); }
public static CloseableHttpClient createHttpClient(final int maxRedirects) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { s_logger.info("Creating new HTTP connection pool and client"); final Registry<ConnectionSocketFactory> socketFactoryRegistry = createSocketFactoryConfigration(); final BasicCookieStore cookieStore = new BasicCookieStore(); final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connManager.setDefaultMaxPerRoute(MAX_ALLOCATED_CONNECTIONS_PER_ROUTE); connManager.setMaxTotal(MAX_ALLOCATED_CONNECTIONS); final RequestConfig requestConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.DEFAULT) .setMaxRedirects(maxRedirects) .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT) .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT) .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT) .build(); return HttpClientBuilder.create() .setConnectionManager(connManager) .setRedirectStrategy(new LaxRedirectStrategy()) .setDefaultRequestConfig(requestConfig) .setDefaultCookieStore(cookieStore) .setRetryHandler(new StandardHttpRequestRetryHandler()) .build(); }
protected CloseableHttpClient createHttpClient(Map<String, Object> parameters) { HttpClientBuilder clientBuilder = HttpClients.custom(); // single connection BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(); clientBuilder.setConnectionManager(connManager); // ignore cookies for now RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); clientBuilder.setDefaultRequestConfig(requestConfig); setAuthentication(parameters, clientBuilder); CloseableHttpClient client = clientBuilder.build(); return client; }
public ProcessConnection(ProcessDirector director, PhantomJSProcess process) { this.process = process; HttpClientBuilder clientBuilder = HttpClients.custom(); // single connection BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(); clientBuilder.setConnectionManager(connManager); RequestConfig requestConfig = RequestConfig.custom() // ignore cookies for now .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .setSocketTimeout(director.getRequestTimeout()).build(); clientBuilder.setDefaultRequestConfig(requestConfig); this.httpClient = clientBuilder.build(); }
@Override public HttpGet initRequest(final UserInfoParameter userInfoParameter) { try { final URIBuilder uriBuilder = new URIBuilder(CONST.URI_PATH); uriBuilder.addParameter(CONST.SRC_KEY, CONST.SRC_VAL); uriBuilder.addParameter(CONST.FROM_KEY, CONST.FROM_VAL); uriBuilder.addParameter(CONST.CHARSET_KEY, CONST.CHARSET_VAL); uriBuilder.addParameter(CONST.METHOD_KEY, CONST.METHOD_VAL); uriBuilder.addParameter(CONST.REQUESTSCEMA_KEY, CONST.REQUESTSCEMA_VAL); uriBuilder.addParameter(CONST.O_KEY, CONST.O_VAL); uriBuilder.addParameter(CONST.SHOW_NAME_FLAG_NAME, CONST.SHOW_NAME_FLAG_VALUE); uriBuilder.addParameter(CONST.HEAD_TYPE_NAME, CONST.HEAD_TYPE_VAL); uriBuilder.addParameter("-", TimeUtil.getTimeLenth(13)); final HttpGet request = new HttpGet(uriBuilder.build()); request.setConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.NETSCAPE).build()); return request; } catch (URISyntaxException e) { LOGGER.error("Error",e); } return null; }
@Override public HttpPost initRequest(final UserCheckLoginParameter userCheckLoginParameter) { setBinaryFilename(LoginConst.USER_INFO_PATH_NAME); Login login = readObjForDisk(Login.class); if(null==login){ login = new Login(); } final HttpPost request = new HttpPost(CONST.URI_PATH); final List<NameValuePair> data = new ArrayList<>(); data.add(new BasicNameValuePair(CONST.QID_NAME, login.getQid())); data.add(new BasicNameValuePair(CONST.METHOD_KEY, CONST.METHOD_VAL)); data.add(new BasicNameValuePair(CONST.AJAX_KEY, CONST.AJAX_VAL)); data.add(new BasicNameValuePair("t", TimeUtil.getTimeLenth(13))); request.setConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.NETSCAPE).build()); request.setEntity(new UrlEncodedFormEntity(data, Consts.UTF_8)); return request; }
protected CookieSpecRegistry createCookieSpecRegistry() { final CookieSpecRegistry registry = new CookieSpecRegistry(); registry.register( CookieSpecs.DEFAULT, new BestMatchSpecFactory()); registry.register( CookiePolicy.BEST_MATCH, new BestMatchSpecFactory()); registry.register( CookiePolicy.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()); registry.register( CookiePolicy.NETSCAPE, new NetscapeDraftSpecFactory()); registry.register( CookiePolicy.RFC_2109, new RFC2109SpecFactory()); registry.register( CookiePolicy.RFC_2965, new RFC2965SpecFactory()); registry.register( CookiePolicy.IGNORE_COOKIES, new IgnoreSpecFactory()); return registry; }
/** * Creates a builder containing the default registry entries, using the provided public suffix matcher. */ public static RegistryBuilder<CookieSpecProvider> createDefaultBuilder(final PublicSuffixMatcher publicSuffixMatcher) { final CookieSpecProvider defaultProvider = new DefaultCookieSpecProvider(publicSuffixMatcher); final CookieSpecProvider laxStandardProvider = new RFC6265CookieSpecProvider( RFC6265CookieSpecProvider.CompatibilityLevel.RELAXED, publicSuffixMatcher); final CookieSpecProvider strictStandardProvider = new RFC6265CookieSpecProvider( RFC6265CookieSpecProvider.CompatibilityLevel.STRICT, publicSuffixMatcher); return RegistryBuilder.<CookieSpecProvider>create() .register(CookieSpecs.DEFAULT, defaultProvider) .register("best-match", defaultProvider) .register("compatibility", defaultProvider) .register(CookieSpecs.STANDARD, laxStandardProvider) .register(CookieSpecs.STANDARD_STRICT, strictStandardProvider) .register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecProvider()) .register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecProvider()); }
@Before public void setUp() { this.target = new HttpHost("localhost.local", 80); this.cookieStore = new BasicCookieStore(); final BasicClientCookie2 cookie1 = new BasicClientCookie2("name1", "value1"); cookie1.setVersion(1); cookie1.setDomain("localhost.local"); cookie1.setPath("/"); this.cookieStore.addCookie(cookie1); final BasicClientCookie2 cookie2 = new BasicClientCookie2("name2", "value2"); cookie2.setVersion(1); cookie2.setDomain("localhost.local"); cookie2.setPath("/"); this.cookieStore.addCookie(cookie2); this.cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create() .register(CookieSpecs.DEFAULT, new DefaultCookieSpecProvider()) .register(CookieSpecs.STANDARD, new RFC2965SpecProvider()) .register(CookieSpecs.NETSCAPE, new NetscapeDraftSpecProvider()) .register(CookieSpecs.IGNORE_COOKIES, new IgnoreSpecProvider()) .build(); }
@Test public void testAddCookiesUsingExplicitCookieSpec() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); final RequestConfig config = RequestConfig.custom() .setCookieSpec(CookieSpecs.NETSCAPE).build(); final HttpRoute route = new HttpRoute(this.target, null, false); final HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target); context.setAttribute(HttpClientContext.HTTP_ROUTE, route); context.setAttribute(HttpClientContext.REQUEST_CONFIG, config); context.setAttribute(HttpClientContext.COOKIE_STORE, this.cookieStore); context.setAttribute(HttpClientContext.COOKIESPEC_REGISTRY, this.cookieSpecRegistry); final HttpRequestInterceptor interceptor = new RequestAddCookies(); interceptor.process(request, context); final CookieSpec cookieSpec = context.getCookieSpec(); Assert.assertTrue(cookieSpec instanceof NetscapeDraftSpec); final Header[] headers1 = request.getHeaders(SM.COOKIE); Assert.assertNotNull(headers1); Assert.assertEquals(1, headers1.length); Assert.assertEquals("name1=value1; name2=value2", headers1[0].getValue()); }
protected void initBase() { SSLContext sslContext = SSLContexts.createSystemDefault(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslContext, SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER); httpRequestConfig = RequestConfig.custom() .setSocketTimeout(TIMEOUT) .setConnectTimeout(TIMEOUT) .setCookieSpec(CookieSpecs.BEST_MATCH) .build(); cookieStore = new BasicCookieStore(); httpClient = HttpClientBuilder.create() .setSSLSocketFactory(sslsf) .setDefaultCookieStore(cookieStore) .setDefaultRequestConfig(httpRequestConfig) .build(); localContext = HttpClientContext.create(); }
@Override public void customize(final HttpClientPlan plan) { checkNotNull(plan); plan.setUserAgentBase(userAgentGenerator.generate()); plan.getClient().setKeepAliveStrategy(new NexusConnectionKeepAliveStrategy(keepAliveDuration.toMillis())); plan.getClient().setRetryHandler(new StandardHttpRequestRetryHandler(2, false)); plan.getConnection().setBufferSize(bufferSize.toBytesI()); plan.getRequest().setConnectionRequestTimeout(connectionRequestTimeout.toMillisI()); plan.getRequest().setCookieSpec(CookieSpecs.IGNORE_COOKIES); plan.getRequest().setExpectContinueEnabled(false); int requestTimeoutMillis = requestTimeout.toMillisI(); plan.getSocket().setSoTimeout(requestTimeoutMillis); plan.getRequest().setConnectTimeout(requestTimeoutMillis); plan.getRequest().setSocketTimeout(requestTimeoutMillis); }
public HttpCon createClient() throws Exception { ArrayList<Header> defheaders = new ArrayList<Header>(); defheaders.add(new BasicHeader("X-Csrf-Token", "1")); BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager( cfgMgr.getHttpClientSocketRegistry()); RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false) .build(); CloseableHttpClient http = HttpClients.custom() .setConnectionManager(bhcm) .setDefaultHeaders(defheaders) .setDefaultRequestConfig(rc) .build(); HttpCon con = new HttpCon(); con.setBcm(bhcm); con.setHttp(http); return con; }
public HttpCon createClient() throws Exception { ArrayList<Header> defheaders = new ArrayList<Header>(); BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager( cfgMgr.getHttpClientSocketRegistry()); RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false) .build(); CloseableHttpClient http = HttpClients.custom() .setConnectionManager(bhcm) .setDefaultHeaders(defheaders) .setDefaultRequestConfig(rc) .build(); HttpCon con = new HttpCon(); con.setBcm(bhcm); con.setHttp(http); return con; }
/** * no-arg constructor for client */ public TankHttpClient4() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE); } catch (Exception e) { LOG.error("Error setting accept all: " + e, e); } httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); requestConfig = RequestConfig.custom().setSocketTimeout(30000) .setConnectTimeout(30000) .setCircularRedirectsAllowed(true) .setAuthenticationEnabled(true) .setRedirectsEnabled(true) .setCookieSpec(CookieSpecs.STANDARD) .setMaxRedirects(100).build(); // Make sure the same context is used to execute logically related // requests context = HttpClientContext.create(); context.setCredentialsProvider(new BasicCredentialsProvider()); context.setCookieStore(new BasicCookieStore()); context.setRequestConfig(requestConfig); }
public NetHTTPGet(NetHTTPResponse r) { resp = r; proxy = null; defaultRequestConfig = RequestConfig .custom() .setConnectTimeout(30000) .setConnectionRequestTimeout(30000) .setContentCompressionEnabled(false) .setMaxRedirects(5) .setSocketTimeout(60000) .setRedirectsEnabled(true) .setRelativeRedirectsAllowed(true) .setCookieSpec(CookieSpecs.STANDARD) .setExpectContinueEnabled(true) .build(); httpClient = HttpClients .custom() .setUserAgent(userAgent) .setDefaultCookieStore(cookieStore) .setDefaultRequestConfig(defaultRequestConfig) .setDefaultCredentialsProvider(credentialsProvider) .build(); }
public OAuthHttpClient(int maxConnection, int connectTimeout, int socketTimeout) { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", SSLConnectionSocketFactory.getSocketFactory()) .build()); // set max connection connectionManager.setMaxTotal(maxConnection); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(connectTimeout) .setSocketTimeout(socketTimeout) .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .build(); httpClient = HttpClientBuilder.create() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)) .build(); }
/** * Creates a {@link org.apache.http.HttpRequest} given a type, path, and optional content. * * @param requestType The type of HTTP/1.1 request to make (see {@link RequestType} * for more details. * @param uri The URI to request content from. * @param args The content of the request. This parameter is optional and considered to be nullable. * * @return A request built from the specification above. */ private HttpUriRequest makeRequest(RequestType requestType, URI uri, Object... args) { RequestConfig.Builder config = RequestConfig.copy(RequestConfig.DEFAULT); config.setCookieSpec(CookieSpecs.BEST_MATCH); RequestBuilder requestBuilder = RequestBuilder.create(requestType.name()) .setUri(uri) .setConfig(config.build()) .setEntity(this.makeEntity(args)) .setHeader("User-Agent", this.getUserAgent()); if (this.oauthToken != null) { requestBuilder.addHeader("Authorization", "Bearer " + this.oauthToken); } if (this.jwt != null) { requestBuilder.addHeader("Authorization", "JWT " + this.jwtString); } if (this.csrfToken != null) { requestBuilder.addHeader(CSRF_TOKEN_HEADER, this.csrfToken); } return requestBuilder.build(); }
@Scheduled(cron = "0 0 9,18 * * ?") public void run() { for (Account account : getAccounts()) { try { RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build(); CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build(); Executor executor = Executor.newInstance(client).use(new BasicCookieStore()); if(login(executor, account)) { checkIn(executor, account); } } catch (Exception e) { log.error("【V2EX】【" + account.getUsername() + "】签到异常", e); } } }
public HttpClientExample(String userAgent) { // 4.3 以上都是通过 RequestConfig 来设置请求的配置项, 如timeout, CookieSpecs // can be set at the HTTP client and overridden on the HTTP request level if required. // HttpClients.custom().setDefaultRequestConfig(globalConfig) // httpGet.setConfig(requestConfig); // 3种timeout // A timeout value of zero is interpreted as an infinite timeout. // A negative value is interpreted as undefined (system default: -1). // 可以通过RequestConfig来设置, 默认为connectionRequestTimeout=0, connectTimeout=0, socketTimeout=0 // 建立连接最终是通过 sock.connect(remoteAddress, connectTimeout); // PlainConnectionSocketFactory.connectSocket // 实际测试中, 即使 connectTimeout=0, 也会在20秒左右超时 // connectionRequestTimeout 获取请求超时时间 // the timeout in milliseconds used when requesting a connection from the connection manager // connectTimeout 连接超时时间 // the timeout in milliseconds until a (Socket) connection is established // socketTimeout 数据传输超时 // the timeout for waiting for data or, put differently, a maximum period inactivity between two consecutive data packets defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build(); // 默认的HttpClient实例连接池只有2/20 hc = HttpClients.custom().setUserAgent(userAgent) .setDefaultRequestConfig(defaultRequestConfig) .build(); }
/** * TODO: Update to use HTTP client "HttpClients....build()" method of creating and tailoring HttpClient * using the proxy and cookie settings, as well as any other tuning. * * Override if your context requires a different style of HTTP client. * * @return HttpClient 4.x object */ public HttpClient getClient() { HttpClientBuilder clientHelper = null; if (this.useSystemProperties) { clientHelper = HttpClientBuilder.create().useSystemProperties(); } else { clientHelper = HttpClientBuilder.create(); if (proxyHost != null) { clientHelper.setProxy(proxyHost); } } RequestConfig globalConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build(); HttpClient httpClient = clientHelper.setDefaultRequestConfig(globalConfig).build(); return httpClient; }
/** * Sharepoint requires NTLM. This client requires a non-null user/passwd/domain. * */ @Override public HttpClient getClient() { if (currentConn!=null){ return currentConn; } HttpClientBuilder clientHelper = HttpClientBuilder.create(); if (proxyHost != null) { clientHelper.setProxy(proxyHost); } RequestConfig globalConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build(); CredentialsProvider creds = new BasicCredentialsProvider(); creds.setCredentials(AuthScope.ANY, new NTCredentials(user, passwd, server, domain)); clientHelper.setDefaultCredentialsProvider(creds); HttpClient httpClient = clientHelper.setDefaultRequestConfig(globalConfig).build(); return httpClient; }
public static CloseableHttpClient newClient(int timeout) { HttpClientBuilder builder = HttpClients.custom(); builder.useSystemProperties(); builder.addInterceptorFirst(REMOVE_INCORRECT_CONTENT_ENCODING); builder.disableAutomaticRetries(); builder.setSSLContext(SSL_CONTEXT); builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE); RequestConfig.Builder configBuilder = RequestConfig.custom(); configBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES); configBuilder.setSocketTimeout(timeout); configBuilder.setConnectTimeout(timeout); configBuilder.setConnectionRequestTimeout(timeout); builder.setDefaultRequestConfig(configBuilder.build()); builder.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Consts.ISO_8859_1).build()); return builder.build(); }
private HttpClient createHttpClient(Authentication auth, String verify, HttpHost target, Boolean postRedirects, String password, TrustStrategy keystoreTrustStrategy, HostnameVerifier keystoreHostnameVerifier, Proxy proxy) { Certificate certificate = new Certificate(); Auth authHelper = new Auth(); HttpClientBuilder httpClientBuilder = WinHttpClients.custom(); Builder requestConfig = RequestConfig.custom(); requestConfig.setCookieSpec(CookieSpecs.DEFAULT); logger.debug("Verify value: " + verify); logger.debug((new File(verify).getAbsolutePath())); if (new File(verify).exists()) { logger.debug("Loading custom keystore"); httpClientBuilder.setSSLSocketFactory( certificate.allowAllCertificates(certificate.createCustomKeyStore(verify.toString(), password), password, keystoreTrustStrategy, keystoreHostnameVerifier)); } else if (!Boolean.parseBoolean(verify.toString())) { logger.debug("Allowing all certificates"); httpClientBuilder.setSSLSocketFactory(certificate.allowAllCertificates(null)); } if (auth.isAuthenticable()) { httpClientBuilder.setDefaultCredentialsProvider(authHelper.getCredentialsProvider(auth, target)); } if (proxy != null && proxy.isInUse()) { logger.debug("Enabling proxy"); if (proxy.isAuthenticable()) { logger.debug("Setting proxy credentials"); httpClientBuilder.setDefaultCredentialsProvider( authHelper.getCredentialsProvider(proxy.getAuth(), proxy.getHttpHost())); } requestConfig.setProxy(proxy.getHttpHost()); } if (postRedirects) { httpClientBuilder.setRedirectStrategy(new CustomRedirectStrategy()); } httpClientBuilder.setDefaultRequestConfig(requestConfig.build()); return httpClientBuilder.build(); }
private CloseableHttpClient createHttpClient() { final RequestConfig requestConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.DEFAULT) .setAuthenticationEnabled(true) .setRedirectsEnabled(true) .build(); return HttpClientBuilder.create() .setDefaultCookieStore(cookieStore) .setDefaultRequestConfig(requestConfig) .build(); }
/** * 描述:创建httpClient连接池,并初始化httpclient */ private void initHttpClient() throws ConfigurationException { Configuration configuration = new PropertiesConfiguration(CONFIG_FILE); //创建httpclient连接池 PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(); httpClientConnectionManager.setMaxTotal(configuration.getInt("http.max.total")); //设置连接池线程最大数量 httpClientConnectionManager.setDefaultMaxPerRoute(configuration.getInt("http.max.route")); //设置单个路由最大的连接线程数量 //创建http request的配置信息 RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(configuration.getInt("http.request.timeout")) .setSocketTimeout(configuration.getInt("http.socket.timeout")) .setCookieSpec(CookieSpecs.DEFAULT).build(); //设置重定向策略 LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy() { /** * false 禁止重定向 true 允许 */ @Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { // TODO Auto-generated method stub return isRediect ? super.isRedirected(request, response, context) : isRediect; } }; //初始化httpclient客户端 httpClient = HttpClients.custom().setConnectionManager(httpClientConnectionManager) .setDefaultRequestConfig(requestConfig) //.setUserAgent(NewsConstant.USER_AGENT) .setRedirectStrategy(redirectStrategy) .build(); }
/** * Sets a Safecharge's default {@link RequestConfig} object to set connection properties like TTL, timeout, etc. * * @return this object */ public SafechargeClientBuilder setDefaultRequestConfig() { this.requestConfig = RequestConfig.custom() .setSocketTimeout(DEFAULT_TIMEOUT_MILLISECONDS) .setConnectTimeout(DEFAULT_TIMEOUT_MILLISECONDS) .setConnectionRequestTimeout(DEFAULT_TIMEOUT_MILLISECONDS) .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .build(); return this; }