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 ApacheHttpClientExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://example.com"); CloseableHttpResponse httpResponse = httpClient.execute(httpGet); System.out.println("Response Code: " + httpResponse.getStatusLine().getStatusCode()); System.out.println("Response Body: " + EntityUtils.toString(httpResponse.getEntity())); httpClient.close(); } } import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class OkHttpExample { public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); String jsonBody = "{\"name\":\"John\", \"age\":30}"; RequestBody body = RequestBody.create(jsonBody, JSON); Request request = new Request.Builder() .url("http://example.com/api") .post(body) .build(); Response response = client.newCall(request).execute(); System.out.println("Response Code: " + response.code()); System.out.println("Response Body: " + response.body().string()); client.close(); } } import org.springframework.web.reactive.function.client.WebClient; public class SpringWebClientExample { public static void main(String[] args) { WebClient client = WebClient.create(); client.get() .uri("http://example.com") .retrieve() .bodyToMono(String.class) .subscribe(response -> { System.out.println("Response Body: " + response); }); } }


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