Beispiele für Apache HttpClient
Dieser Artikel zeigt Ihnen, wie SieApache HttpClient zum Senden von HTTP-GET / POST-Anforderungen, JSON, Authentifizierung, Zeitüberschreitung, Umleitung und einigen häufig verwendeten Beispielen verwenden.
P.S Tested with HttpClient 4.5.10
pom.xml
org.apache.httpcomponents httpclient 4.5.10
1. GET-Anfrage senden
1.1 Close manually.
HttpClientExample1_1.java
package com.example.http; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpClientExample1_1 { public static void main(String[] args) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpGet request = new HttpGet("https://httpbin.org/get"); // add request headers request.addHeader("custom-key", "example"); request.addHeader(HttpHeaders.USER_AGENT, "Googlebot"); CloseableHttpResponse response = httpClient.execute(request); try { // Get HttpResponse Status System.out.println(response.getProtocolVersion()); // HTTP/1.1 System.out.println(response.getStatusLine().getStatusCode()); // 200 System.out.println(response.getStatusLine().getReasonPhrase()); // OK System.out.println(response.getStatusLine().toString()); // HTTP/1.1 200 OK HttpEntity entity = response.getEntity(); if (entity != null) { // return it as a String String result = EntityUtils.toString(entity); System.out.println(result); } } finally { response.close(); } } finally { httpClient.close(); } } }
1.2 Close with try-with-resources.
HttpClientExample1_2.java
package com.example.http; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpClientExample1_2 { public static void main(String[] args) throws IOException { HttpGet request = new HttpGet("https://httpbin.org/get"); // add request headers request.addHeader("custom-key", "example"); request.addHeader(HttpHeaders.USER_AGENT, "Googlebot"); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(request)) { // Get HttpResponse Status System.out.println(response.getProtocolVersion()); // HTTP/1.1 System.out.println(response.getStatusLine().getStatusCode()); // 200 System.out.println(response.getStatusLine().getReasonPhrase()); // OK System.out.println(response.getStatusLine().toString()); // HTTP/1.1 200 OK HttpEntity entity = response.getEntity(); if (entity != null) { // return it as a String String result = EntityUtils.toString(entity); System.out.println(result); } } } }
2. Normale POST-Anfrage senden
HttpClientExample2_1.java
package com.example.http; import org.apache.http.HttpHeaders; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class HttpClientExample2_1 { public static void main(String[] args) { try { String result = sendPOST("https://httpbin.org/post"); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } } private static String sendPOST(String url) throws IOException { String result = ""; HttpPost post = new HttpPost(url); // add request parameters or form parameters ListurlParameters = new ArrayList<>(); urlParameters.add(new BasicNameValuePair("username", "abc")); urlParameters.add(new BasicNameValuePair("password", "123")); urlParameters.add(new BasicNameValuePair("custom", "secret")); post.setEntity(new UrlEncodedFormEntity(urlParameters)); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(post)){ result = EntityUtils.toString(response.getEntity()); } return result; } }
3. JSON-POST-Anfrage senden
3.1 Send a POST request with JSON formatted data. Dem Schlüssel wird das JSON-formatierte Datum inStringEntity
übergeben.
HttpClientExample3_1.java
package com.example.http; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpClientExample3_1 { public static void main(String[] args) { try { String result = sendPOST("https://httpbin.org/post"); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } } private static String sendPOST(String url) throws IOException { String result = ""; HttpPost post = new HttpPost(url); StringBuilder json = new StringBuilder(); json.append("{"); json.append("\"name\":\"example\","); json.append("\"notes\":\"hello\""); json.append("}"); // send a JSON data post.setEntity(new StringEntity(json.toString())); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(post)) { result = EntityUtils.toString(response.getEntity()); } return result; } }
3.2 Send a POST request to Cloudflare API to block an IP address. Authentifizierung in Headern.
HttpClientExample3_2.java
package com.example.http; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpClientExample3_2 { public static void main(String[] args) { try { String result = blockIP("1.1.1.1"); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } } private static String blockIP(String ip) throws IOException { String result = ""; HttpPost post = new HttpPost("https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules"); post.addHeader("content-type", "application/json"); post.addHeader("X-Auth-Email", "email"); post.addHeader("X-Auth-Key", "token123"); String block = "{\"target\":\"ip\",\"value\":\"" + ip + "\"}"; StringBuilder entity = new StringBuilder(); entity.append("{"); entity.append("\"mode\":\"block\","); entity.append("\"configuration\":" + block + ","); entity.append("\"notes\":\"hello\""); entity.append("}"); // send a JSON data post.setEntity(new StringEntity(entity.toString())); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(post)) { result = EntityUtils.toString(response.getEntity()); } return result; } }
4. HTTP-Basisauthentifizierung
HttpClientExample4_1.java
package com.example.http; import org.apache.http.HttpEntity; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpClientExample4_1 { public static void main(String[] args) throws IOException { HttpGet request = new HttpGet("http://localhost:8080/books"); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials( AuthScope.ANY, new UsernamePasswordCredentials("user", "password") ); try (CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultCredentialsProvider(provider) .build(); CloseableHttpResponse response = httpClient.execute(request)) { // 401 if wrong user/password System.out.println(response.getStatusLine().getStatusCode()); HttpEntity entity = response.getEntity(); if (entity != null) { // return it as a String String result = EntityUtils.toString(entity); System.out.println(result); } } } }
Lesen Sie dies -Apache HttpClient Basic Authentication Examples
5. FAQs
5.1 Disabled Redirect.
HttpClientExample5_1.java
package com.example.customer; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpClientExample5_1 { public static void main(String[] args) throws IOException { HttpGet request = new HttpGet("https://t.co/calv72DH8f"); request.addHeader(HttpHeaders.USER_AGENT, "Googlebot"); try (CloseableHttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build(); CloseableHttpResponse response = httpClient.execute(request)) { // Get HttpResponse Status System.out.println(response.getProtocolVersion()); // HTTP/1.1 System.out.println(response.getStatusLine().getStatusCode()); // 301 System.out.println(response.getStatusLine().getReasonPhrase()); // Moved Permanently System.out.println(response.getStatusLine().toString()); // HTTP/1.1 301 Moved Permanently HttpEntity entity = response.getEntity(); if (entity != null) { // return it as a String String result = EntityUtils.toString(entity); System.out.println(result); } } } }
5.2 Connection time out on request level.
HttpGet request = new HttpGet("https://httpbin.org/get"); // 5 seconds timeout RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(5000) .setConnectTimeout(5000) .setSocketTimeout(5000) .build(); request.setConfig(requestConfig); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(request)) { //... }
5.3 Connection time out on client level.
HttpGet request = new HttpGet("https://httpbin.org/get"); // 5 seconds timeout RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(5000) .setConnectTimeout(5000) .setSocketTimeout(5000) .build(); //request.setConfig(requestConfig); try (CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultRequestConfig(requestConfig) .build(); CloseableHttpResponse response = httpClient.execute(request)) { //... }
5.4 Configure a proxy server. Lesen SieHttpClient proxy configuration
HttpGet request = new HttpGet("https://httpbin.org/get"); RequestConfig requestConfig = RequestConfig.custom() .setProxy(new HttpHost("company.proxy.url", 8080)) .build(); request.setConfig(requestConfig); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(request)) { //... }
5.5 Turn on cookie. Lesen SieHTTP cookies
HttpGet request = new HttpGet("https://httpbin.org/get"); RequestConfig requestConfig = RequestConfig.custom() .setCookieSpec(CookieSpecs.DEFAULT) .build(); request.setConfig(requestConfig); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(request)) { //... }
5.6 Get response header and also the media type.
try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(request)) { HttpEntity entity = response.getEntity(); Header headers = entity.getContentType(); System.out.println(headers); //... }
Stichprobe
Content-Type: application/json { "args": {}, "headers": { "Accept-Encoding": "gzip,deflate", "Custom-Key": "example", "Host": "httpbin.org", "User-Agent": "Googlebot" }, "origin": "202.168.71.227, 202.168.71.227", "url": "https://httpbin.org/get" }