1. Apache HttpClient 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; public class HttpClientExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("https://api.example.com/"); HttpResponse response = httpclient.execute(httpGet); System.out.println(response.getStatusLine()); httpclient.close(); } } 2. OkHttp import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class OkHttpExample { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://api.example.com/") .build(); Response response = client.newCall(request).execute(); System.out.println(response.code()); response.close(); } } 3. Spring RestTemplate import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class RestTemplateExample { public static void main(String[] args) throws Exception { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> responseEntity = restTemplate.getForEntity("https://api.example.com/", String.class); int statusCode = responseEntity.getStatusCodeValue(); System.out.println(statusCode); } } import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class HttpClientConfigExample { public static void main(String[] args) throws Exception { RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000) .build(); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultRequestConfig(requestConfig) .setUserAgent("My User Agent") .build(); HttpGet httpGet = new HttpGet("https://api.example.com/"); HttpResponse response = httpclient.execute(httpGet); System.out.println(response.getStatusLine()); httpclient.close(); } }


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