1. Apache HttpClient: import org.apache.http.HttpEntity; 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; public class HttpClientExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://example.com"); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); System.out.println(responseBody); } } } 2. OkHttp: import okhttp3.*; import java.io.IOException; public class OkHttpExample { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "{\"key\":\"value\"}"); Request request = new Request.Builder() .url("http://example.com") .post(body) .build(); try (Response response = client.newCall(request).execute()) { System.out.println(response.body().string()); } } } 3. HttpURLConnection: import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLConnectionExample { public static void main(String[] args) throws Exception { URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); try (BufferedReader reader = new BufferedReader( new InputStreamRead(new connection.getInputStream()))) { String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } System.out.println(response.toString()); } } }


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