當前位置: 首頁>>代碼示例>>Java>>正文


Java RequestConfig類代碼示例

本文整理匯總了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");
    }
}
 
開發者ID:yacy,項目名稱:yacy_grid_mcp,代碼行數:34,代碼來源:ClientConnection.java

示例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;
}
 
開發者ID:fabzo,項目名稱:kraken,代碼行數:26,代碼來源:HTTPWait.java

示例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;
}
 
開發者ID:telstra,項目名稱:open-kilda,代碼行數:35,代碼來源:Mininet.java

示例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);

}
 
開發者ID:NationalSecurityAgency,項目名稱:qonduit,代碼行數:37,代碼來源:HTTPStrictTransportSecurityIT.java

示例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();
  }
}
 
開發者ID:11590692,項目名稱:Wechat-Group,代碼行數:22,代碼來源:WxMpPayServiceImpl.java

示例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);
}
 
開發者ID:a483210,項目名稱:GoogleTranslation,代碼行數:18,代碼來源:HttpPostParams.java

示例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();
	}
}
 
開發者ID:swxiao,項目名稱:bubble2,代碼行數:26,代碼來源:HttpUtils.java

示例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) {
        }
    }
}
 
開發者ID:StevenKin,項目名稱:ZhihuQuestionsSpider,代碼行數:17,代碼來源:ProxyPool.java

示例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();
}
 
開發者ID:hmcts,項目名稱:cmc-claim-store,代碼行數:18,代碼來源:HttpClientConfiguration.java

示例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();
        }
    }
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:23,代碼來源:HttpClientUtils.java

示例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);
  }
}
 
開發者ID:XecureIT,項目名稱:PeSanKita-android,代碼行數:20,代碼來源:OutgoingLegacyMmsConnection.java

示例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();
}
 
開發者ID:MinsxCloud,項目名稱:minsx-java-example,代碼行數:34,代碼來源:RemoteServerClientImpl.java

示例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();
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:19,代碼來源:RestClientBuilder.java

示例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();
}
 
開發者ID:SeldonIO,項目名稱:seldon-core,代碼行數:19,代碼來源:InternalPredictionService.java

示例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();
}
 
開發者ID:samurayrj,項目名稱:rubenlagus-TelegramBots,代碼行數:24,代碼來源:DefaultBotSession.java


注:本文中的org.apache.http.client.config.RequestConfig類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。