本文整理匯總了Java中org.apache.http.impl.client.HttpClients類的典型用法代碼示例。如果您正苦於以下問題:Java HttpClients類的具體用法?Java HttpClients怎麽用?Java HttpClients使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
HttpClients類屬於org.apache.http.impl.client包,在下文中一共展示了HttpClients類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: client
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
@Test
public void client() throws URISyntaxException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.google.com")
.setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "")
.build();
HttpGet httpget = new HttpGet(uri);
CloseableHttpResponse response = httpclient.execute(httpget);
}
示例2: notifyHunter
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
public String notifyHunter(byte[] content) throws IOException {
try {
String request = new String(content);
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection");
String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}";
StringEntity entity = new StringEntity(json);
entity.setContentType("applicaiton/json");
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String responseString = new BasicResponseHandler().handleResponse(response);
return responseString;
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex);
}
return "Error Notifying Probe Server!";
}
示例3: restTemplate
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslConnectionSocketFactory)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
}
示例4: readAggregates
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
public ReadAggregatesResult readAggregates() throws IOException, PyroclastAPIException {
ensureBaseAttributes();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
String url = String.format("%s/%s/aggregates", this.buildEndpoint(), this.deploymentId);
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Authorization", this.readApiKey);
httpGet.addHeader("Content-type", FORMAT);
ReadAggregatesResult result;
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
ResponseParser<ReadAggregatesResult> parser = new ReadAggregatesParser();
result = parser.parseResponse(response, MAPPER);
}
return result;
}
}
示例5: buildHttpClient
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
/**
* 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();
}
示例6: test1
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
@Test
public void test1(){
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(
"http://hncjzf.bibibi.net/module/getcareers?start=0&count=50&keyword=&address=&professionals=&career_type=&type=inner&day=2017-11-08");
HttpResponse response = httpClient.execute(httpGet);
JSONObject object = JSON.parseObject(EntityUtils.toString(response.getEntity()));
JSONArray data = object.getJSONArray("data");
List<HUELList> list = JSON.parseArray(data.toJSONString(), HUELList.class);
//HUELList list1 = list.get(0);
huelService.saveList(list);
}catch (IOException e){
}
}
示例7: get
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
public static HttpResponse get(String url, Map<String, String> header) {
int statusCode = 0;
String responseBody = "";
try {
logger.info(String.format("Getting url: %s", url));
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(url);
if (header != null && !header.isEmpty()) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
statusCode = httpResponse.getStatusLine().getStatusCode();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()))) {
responseBody = IOUtils.toString(reader);
logger.info(String.format("Finished getting url: %s, Http status: %s, Response body: %s",
url, statusCode, truncateLogString(responseBody)));
}
}
}
return new HttpResponse(statusCode, responseBody);
} catch (Exception ex) {
String msg = String.format("Failed getting url: %s", url);
logger.warn(msg, ex);
throw new RuntimeException(msg, ex);
}
}
示例8: InternalPredictionService
import org.apache.http.impl.client.HttpClients; //導入依賴的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();
}
示例9: read
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
/**
* Returns the content read form content-source.
* @return read {@link Content}
*/
@Override
public Content[] read(final FetchHistory lastFetch) {
final CloseableHttpClient httpClient = HttpClients.createDefault();
final HttpGet httpget = new HttpGet(contentSource.getUrl());
final HttpContext context = new BasicHttpContext();
CloseableHttpResponse response = null;
String stringRead = null;
try {
try {
LOGGER.info("Loading uri: " + httpget.getURI());
response = httpClient.execute(httpget, context);
final HttpEntity entity = response.getEntity();
if (entity != null) {
stringRead = IOUtils.toString(entity.getContent());
LOGGER.info("Read {} bytes from: {}", stringRead.getBytes().length, httpget.getURI());
}
} finally {
CloseUtil.close(response);
CloseUtil.close(httpClient);
}
} catch (final Exception e) {
LOGGER.warn("Error occurred while reading text document: " + contentSource.getUrl());
}
return new Content[] { createContentObject(stringRead) };
}
示例10: onOpenLsp_timeout
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
@Test
public void onOpenLsp_timeout() {
// HttpClient for WSSynchronize notification
mockStatic(HttpClients.class);
expect(HttpClients.createSystem()).andReturn(dummyHttpClient);
replayAll();
Map<String, List<String>> reqParam = new HashMap<>();
reqParam.put("lsp_timeout", Arrays.asList("100"));
Session testSessionTO = Mockito.spy(Session.class);
Mockito.when(testSessionTO.getRequestParameterMap()).thenReturn(reqParam);
Mockito.when(testSessionTO.getId()).thenReturn("0");
Mockito.when(testSessionTO.getNegotiatedSubprotocol()).thenReturn("access_token");
Mockito.when(testSessionTO.getBasicRemote()).thenReturn(remoteEndpointMock);
doReturn("/").when(lspProcessMock).getProjPath();
cut.onOpen("testWS", "aLang", testSessionTO, endpointConfig);
Mockito.verify(testSessionTO, times(1)).setMaxIdleTimeout(100L);
assertEquals(READY_MESSAGE, readyMessage);
assertEquals("Wrong registration data ", "/:aLang=/testWS/aLang", TestUtils.getInternalState(dummyHttpClient, "regData"));
}
示例11: initHttpClient
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
private void initHttpClient() {
this.connectionManager.setMaxTotal(this.clientConfig.getMaxConnectionsCount());
this.connectionManager.setDefaultMaxPerRoute(this.clientConfig.getMaxConnectionsCount());
this.connectionManager.setValidateAfterInactivity(1);
HttpClientBuilder httpClientBuilder =
HttpClients.custom().setConnectionManager(connectionManager);
if (this.clientConfig.getHttpProxyIp() != null
&& this.clientConfig.getHttpProxyPort() != 0) {
HttpHost proxy = new HttpHost(this.clientConfig.getHttpProxyIp(),
this.clientConfig.getHttpProxyPort());
httpClientBuilder.setProxy(proxy);
}
this.httpClient = httpClientBuilder.build();
this.requestConfig =
RequestConfig.custom()
.setConnectionRequestTimeout(
this.clientConfig.getConnectionRequestTimeout())
.setConnectTimeout(this.clientConfig.getConnectionTimeout())
.setSocketTimeout(this.clientConfig.getSocketTimeout()).build();
this.idleConnectionMonitor = new IdleConnectionMonitorThread(this.connectionManager);
this.idleConnectionMonitor.start();
}
示例12: readAggregateGroup
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
public ReadAggregateGroupResult readAggregateGroup(String aggregateName, String groupName) throws IOException, PyroclastAPIException {
ensureBaseAttributes();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
String url = String.format("%s/%s/aggregates/%s/group/%s",
this.buildEndpoint(), this.deploymentId, aggregateName, groupName);
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Authorization", this.readApiKey);
httpGet.addHeader("Content-type", FORMAT);
ReadAggregateGroupResult result;
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
ResponseParser<ReadAggregateGroupResult> parser = new ReadAggregateGroupParser();
result = parser.parseResponse(response, MAPPER);
}
return result;
}
}
示例13: usingHttpComponents
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options)
throws GeneralSecurityException, IOException {
HttpClientBuilder httpClientBuilder = HttpClients.custom()
.setSSLContext(SSLContext.getDefault())
.useSystemProperties();
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
.setAuthenticationEnabled(true);
if (options.getConnectionTimeout() != null) {
requestConfigBuilder.setConnectTimeout(options.getConnectionTimeout());
}
if (options.getReadTimeout() != null) {
requestConfigBuilder.setSocketTimeout(options.getReadTimeout());
}
httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
}
示例14: connect
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
public Map<String, String> connect(String url, Map<String, Object> parameters) throws ManagerResponseException {
Map<String, String> response = new HashMap<String, String>();
CloseableHttpClient httpclient = HttpClients.createDefault();
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login")));
nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password")));
localContext = HttpClientContext.create();
localContext.setCookieStore(new BasicCookieStore());
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
ResponseHandler<String> handler = new CustomResponseErrorHandler();
String body = handler.handleResponse(httpResponse);
response.put(BODY, body);
httpResponse.close();
} catch (Exception e) {
authentificationUtils.getMap().clear();
throw new ManagerResponseException(e.getMessage(), e);
}
return response;
}
示例15: getEntity
import org.apache.http.impl.client.HttpClients; //導入依賴的package包/類
private String getEntity(URI url) throws IOException {
final HttpGet get = new HttpGet(url);
get.setConfig(requestConfig);
get.setHeader("Accept", "application/json");
HttpClientBuilder clientBuilder = HttpClients.custom();
if (sslContext != null) {
clientBuilder.setSslcontext(sslContext);
}
try (CloseableHttpClient httpClient = clientBuilder.build()) {
try (CloseableHttpResponse response = httpClient.execute(get)) {
final StatusLine statusLine = response.getStatusLine();
final int statusCode = statusLine.getStatusCode();
if (200 != statusCode) {
final String msg = String.format("Failed to get entity from %s, response=%d:%s",
get.getURI(), statusCode, statusLine.getReasonPhrase());
throw new RuntimeException(msg);
}
final HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}
}
}