Java 中进行 HTTP 接口请求的方式有多种,常用的方式包括使用 Java 原生的 HttpURLConnection 类、Apache HttpClient 库和 Spring 的 RestTemplate。
使用 HttpURLConnection 类进行 HTTP 接口请求:
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) { try { // 创建 URL 对象 URL url = new URL("http://example.com/api/endpoint"); // 打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法 connection.setRequestMethod("GET"); // 发送请求 int responseCode = connection.getResponseCode(); // 读取响应 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 关闭连接 connection.disconnect(); // 处理响应 System.out.println("Response Code: " + responseCode); System.out.println("Response Body: " + response.toString()); } catch (Exception e) { e.printStackTrace(); } } }
使用 Apache HttpClient 库进行 HTTP 接口请求:
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class ApacheHttpClientExample { public static void main(String[] args) { try { // 创建 HttpClient 对象 HttpClient httpClient = HttpClients.createDefault(); // 创建 HttpGet 请求对象 HttpGet httpGet = new HttpGet("http://example.com/api/endpoint"); // 发送请求并获取响应 HttpResponse response = httpClient.execute(httpGet); // 读取响应 HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); // 处理响应 System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); System.out.println("Response Body: " + responseBody); } catch (Exception e) { e.printStackTrace(); } } }
使用 Spring 的 RestTemplate 进行 HTTP 接口请求(需要添加相关依赖):
import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class RestTemplateExample { public static void main(String[] args) { try { // 创建 RestTemplate 对象 RestTemplate restTemplate = new RestTemplate(); // 发送 GET 请求并获取响应 ResponseEntity<String> response = restTemplate.getForEntity("http://example.com/api/endpoint", String.class); // 处理响应 System.out.println("Response Code: " + response.getStatusCode()); System.out.println("Response Body: " + response.getBody()); } catch (Exception e) { e.printStackTrace(); } } }
通过以上示例,你可以根据需要选择合适的方式来进行 Java 中的 HTTP 接口请求,以便与其他服务进行数据交互。