本文整理汇总了Java中org.apache.http.client.config.RequestConfig类的典型用法代码示例。如果您正苦于以下问题:Java RequestConfig类的具体用法?Java RequestConfig怎么用?Java RequestConfig使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
RequestConfig类属于org.apache.http.client.config包,在下文中一共展示了RequestConfig类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getRedirect
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
/**
* get a redirect for an url: this method shall be called if it is expected that a url
* is redirected to another url. This method then discovers the redirect.
* @param urlstring
* @param useAuthentication
* @return the redirect url for the given urlstring
* @throws IOException if the url is not redirected
*/
public static String getRedirect(String urlstring) throws IOException {
HttpGet get = new HttpGet(urlstring);
get.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
get.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
CloseableHttpClient httpClient = getClosableHttpClient();
HttpResponse httpResponse = httpClient.execute(get);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
if (httpResponse.getStatusLine().getStatusCode() == 301) {
for (Header header: httpResponse.getAllHeaders()) {
if (header.getName().equalsIgnoreCase("location")) {
EntityUtils.consumeQuietly(httpEntity);
return header.getValue();
}
}
EntityUtils.consumeQuietly(httpEntity);
throw new IOException("redirect for " + urlstring+ ": no location attribute found");
} else {
EntityUtils.consumeQuietly(httpEntity);
throw new IOException("no redirect for " + urlstring+ " fail: " + httpResponse.getStatusLine().getStatusCode() + ": " + httpResponse.getStatusLine().getReasonPhrase());
}
} else {
throw new IOException("client connection to " + urlstring + " fail: no connection");
}
}
示例2: execute
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
@Override
public boolean execute(final EnvironmentContext ctx, final InfrastructureComponent component) {
val defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(2000)
.setSocketTimeout(2000)
.setConnectionRequestTimeout(2000)
.build();
val httpClient = HttpClients.custom()
.setConnectionManager(new BasicHttpClientConnectionManager())
.setDefaultRequestConfig(defaultRequestConfig)
.build();
await().atMost(atMost.toMillis(), TimeUnit.MILLISECONDS).until(() -> {
try {
val response = httpClient.execute(new HttpGet(url));
val result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
return containsText != null && result.contains(containsText);
} catch(final Exception ignored) {
return false;
}
});
return true;
}
示例3: simpleGet
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
/**
* Simple Http Get.
*
* @param path the path
* @return the CloseableHttpResponse
* @throws URISyntaxException the URI syntax exception
* @throws IOException Signals that an I/O exception has occurred.
* @throws MininetException the MininetException
*/
public CloseableHttpResponse simpleGet(String path)
throws URISyntaxException, IOException, MininetException {
URI uri = new URIBuilder()
.setScheme("http")
.setHost(mininetServerIP.toString())
.setPort(mininetServerPort.getPort())
.setPath(path)
.build();
CloseableHttpClient client = HttpClientBuilder.create().build();
RequestConfig config = RequestConfig
.custom()
.setConnectTimeout(CONNECTION_TIMEOUT_MS)
.setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
.setSocketTimeout(CONNECTION_TIMEOUT_MS)
.build();
HttpGet request = new HttpGet(uri);
request.setConfig(config);
request.addHeader("Content-Type", "application/json");
CloseableHttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() >= 300) {
throw new MininetException(String.format("failure - received a %d for %s.",
response.getStatusLine().getStatusCode(), request.getURI().toString()));
}
return response;
}
示例4: testHttpRequestGet
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
@Test
public void testHttpRequestGet() throws Exception {
RequestConfig.Builder req = RequestConfig.custom();
req.setConnectTimeout(5000);
req.setConnectionRequestTimeout(5000);
req.setRedirectsEnabled(false);
req.setSocketTimeout(5000);
req.setExpectContinueEnabled(false);
HttpGet get = new HttpGet("http://127.0.0.1:54322/login");
get.setConfig(req.build());
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setDefaultMaxPerRoute(5);
HttpClientBuilder builder = HttpClients.custom();
builder.disableAutomaticRetries();
builder.disableRedirectHandling();
builder.setConnectionTimeToLive(5, TimeUnit.SECONDS);
builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
builder.setConnectionManager(cm);
CloseableHttpClient client = builder.build();
String s = client.execute(get, new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
assertEquals(301, response.getStatusLine().getStatusCode());
return "success";
}
});
assertEquals("success", s);
}
示例5: executeRequest
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
private String executeRequest(String url, String requestStr) throws WxErrorException {
HttpPost httpPost = new HttpPost(url);
if (this.wxMpService.getHttpProxy() != null) {
httpPost.setConfig(RequestConfig.custom().setProxy(this.wxMpService.getHttpProxy()).build());
}
try (CloseableHttpClient httpclient = HttpClients.custom().build()) {
httpPost.setEntity(new StringEntity(new String(requestStr.getBytes("UTF-8"), "ISO-8859-1")));
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
String result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
this.log.debug("\n[URL]: {}\n[PARAMS]: {}\n[RESPONSE]: {}", url, requestStr, result);
return result;
}
} catch (IOException e) {
this.log.error("\n[URL]: {}\n[PARAMS]: {}\n[EXCEPTION]: {}", url, requestStr, e.getMessage());
throw new WxErrorException(WxError.newBuilder().setErrorCode(-1).setErrorMsg(e.getMessage()).build(), e);
} finally {
httpPost.releaseConnection();
}
}
示例6: send
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
@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);
}
示例7: HttpUtils
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
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();
}
}
示例8: checkProxys
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
public void checkProxys(){
while(true){
Proxy proxy = this.poplProxy();
HttpHost host = new HttpHost(proxy.getIp(),proxy.getPort());
RequestConfig config = RequestConfig.custom().setProxy(host).build();
HttpGet httpGet = new HttpGet(PROXY_TEST_URL);
httpGet.setConfig(config);
try {
CloseableHttpResponse response = this.httpClient.execute(httpGet);
String content = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
if(content!=null&&content.trim().equals(proxy.getIp()))
this.pushrProxy(proxy);
} catch (IOException e) {
}
}
}
示例9: getHttpClient
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
private CloseableHttpClient getHttpClient() {
int timeout = 10000;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setSocketTimeout(timeout)
.build();
return HttpClientBuilder
.create()
.useSystemProperties()
.addInterceptorFirst(new OutboundRequestIdSettingInterceptor())
.addInterceptorFirst((HttpRequestInterceptor) new OutboundRequestLoggingInterceptor())
.addInterceptorLast((HttpResponseInterceptor) new OutboundRequestLoggingInterceptor())
.setDefaultRequestConfig(config)
.build();
}
示例10: getMethodGetContent
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
/**
* HttpClient get方法请求返回Entity
*/
private static byte[] getMethodGetContent(String address,
RequestConfig config) throws Exception {
HttpGet get = new HttpGet(address);
try {
get.setConfig(config);
HttpResponse response = CLIENT.execute(get);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
int code = response.getStatusLine().getStatusCode();
throw new RuntimeException("HttpGet Access Fail , Return Code("
+ code + ")");
}
response.getEntity().getContent();
return convertEntityToBytes(response.getEntity());
} finally {
if (get != null) {
get.releaseConnection();
}
}
}
示例11: constructRequest
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
private HttpUriRequest constructRequest(byte[] pduBytes, boolean useProxy)
throws IOException
{
try {
HttpPostHC4 request = new HttpPostHC4(apn.getMmsc());
for (Header header : getBaseHeaders()) {
request.addHeader(header);
}
request.setEntity(new ByteArrayEntityHC4(pduBytes));
if (useProxy) {
HttpHost proxy = new HttpHost(apn.getProxy(), apn.getPort());
request.setConfig(RequestConfig.custom().setProxy(proxy).build());
}
return request;
} catch (IllegalArgumentException iae) {
throw new IOException(iae);
}
}
示例12: testPost
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
@Test
public void testPost() throws IOException {
String ip = "冰箱冰箱冰箱冰箱冰箱冰箱冰箱";
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
// 请求参数
StringEntity entity = new StringEntity("", DEFAULT_ENCODE);
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
HttpPost httpPost = new HttpPost("https://m.fangliaoyun.com");
httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
//此处区别PC终端类型
httpPost.addHeader("typeFlg", "9");
//此处增加浏览器端访问IP
httpPost.addHeader("x-forwarded-for", ip);
httpPost.addHeader("Proxy-Client-IP", ip);
httpPost.addHeader("WL-Proxy-Client-IP", ip);
httpPost.addHeader("HTTP_CLIENT_IP", ip);
httpPost.addHeader("X-Real-IP", ip);
httpPost.addHeader("Host", ip);
httpPost.setEntity(entity);
httpPost.setConfig(RequestConfig.DEFAULT);
HttpResponse httpResponse;
// post请求
httpResponse = closeableHttpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println(httpEntity.getContent());
//释放资源
closeableHttpClient.close();
}
示例13: createHttpClient
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
private CloseableHttpAsyncClient createHttpClient() {
//default timeouts are all infinite
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS)
.setSocketTimeout(DEFAULT_SOCKET_TIMEOUT_MILLIS)
.setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT_MILLIS);
if (requestConfigCallback != null) {
requestConfigBuilder = requestConfigCallback.customizeRequestConfig(requestConfigBuilder);
}
HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClientBuilder.create().setDefaultRequestConfig(requestConfigBuilder.build())
//default settings for connection pooling may be too constraining
.setMaxConnPerRoute(DEFAULT_MAX_CONN_PER_ROUTE).setMaxConnTotal(DEFAULT_MAX_CONN_TOTAL);
if (httpClientConfigCallback != null) {
httpClientBuilder = httpClientConfigCallback.customizeHttpClient(httpClientBuilder);
}
return httpClientBuilder.build();
}
示例14: InternalPredictionService
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
@Autowired
public InternalPredictionService(AppProperties appProperties){
this.appProperties = appProperties;
connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(150);
connectionManager.setDefaultMaxPerRoute(150);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(DEFAULT_REQ_TIMEOUT)
.setConnectTimeout(DEFAULT_CON_TIMEOUT)
.setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).build();
httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(new HttpRetryHandler())
.build();
}
示例15: start
import org.apache.http.client.config.RequestConfig; //导入依赖的package包/类
@Override
public synchronized void start() {
httpclient = HttpClientBuilder.create()
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.setConnectionTimeToLive(70, TimeUnit.SECONDS)
.setMaxConnTotal(100)
.build();
requestConfig = options.getRequestConfig();
exponentialBackOff = options.getExponentialBackOff();
if (exponentialBackOff == null) {
exponentialBackOff = new ExponentialBackOff();
}
if (requestConfig == null) {
requestConfig = RequestConfig.copy(RequestConfig.custom().build())
.setSocketTimeout(SOCKET_TIMEOUT)
.setConnectTimeout(SOCKET_TIMEOUT)
.setConnectionRequestTimeout(SOCKET_TIMEOUT).build();
}
super.start();
}