<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet("http://api.example.com/data"); try { HttpResponse response = httpClient.execute(httpGet); String responseBody = EntityUtils.toString(response.getEntity()); System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); System.out.println("Response Body: " + responseBody); } catch (Exception e) { e.printStackTrace(); } } } import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class HttpClientConfigurationExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://api.example.com/data"); httpPost.setHeader("Content-Type", "application/json"); StringEntity entity = new StringEntity("{\"name\":\"John\",\"age\":30}", ContentType.APPLICATION_JSON); httpPost.setEntity(entity); httpClient.getParams().setParameter("http.connection.timeout", 5000); try { HttpResponse response = httpClient.execute(httpPost); String responseBody = EntityUtils.toString(response.getEntity()); System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); System.out.println("Response Body: " + responseBody); } catch (Exception e) { e.printStackTrace(); } } }


上一篇:
下一篇:
切换中文