说明
Java调用HTTP接口可以使用Java的HttpURLConnection或HttpClient等工具
HttpURLConnection
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;public class HttpExample {public static void main(String[] args) throws Exception {// 创建URL对象URL url = new URL("http://example.com/api");// 创建HttpURLConnection对象HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 设置请求方法为GETconn.setRequestMethod("GET");// 发送请求int responseCode = conn.getResponseCode();// 读取响应内容BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));String inputLine;StringBuffer response = new StringBuffer();while ((inputLine = in.readLine()) != null) {response.append(inputLine);}in.close();// 打印响应内容System.out.println(response.toString());}
}
HttpClient
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;public class HttpExample {public static void main(String[] args) throws Exception {// 创建HttpClient对象HttpClient client = HttpClientBuilder.create().build();// 创建HttpGet对象HttpGet request = new HttpGet("http://example.com/api");// 发送请求HttpResponse response = client.execute(request);// 读取响应内容BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));String inputLine;StringBuffer responseBuffer = new StringBuffer();while ((inputLine = in.readLine()) != null) {responseBuffer.append(inputLine);}in.close();// 打印响应内容System.out.println(responseBuffer.toString());}
}