1. Apache HttpClient: import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; 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 ApacheHttpClientExample { public static void main(String[] args) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://example.com/api"); try { HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity); System.out.println(result); } } catch (IOException e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } } 2. OkHttp: import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class OkHttpExample { public static void main(String[] args) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://example.com/api") .build(); try { Response response = client.newCall(request).execute(); String result = response.body().string(); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } } } 3. Spring RestTemplate: import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class RestTemplateExample { public static void main(String[] args) { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity("http://example.com/api", String.class); String result = response.getBody(); System.out.println(result); } }


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