说明
Java调用HTTP接口可以使用Java的HttpURLConnection或HttpClient等工具文章来源地址https://www.toymoban.com/news/detail-714668.html
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();
// 设置请求方法为GET
conn.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());
}
}
文章来源:https://www.toymoban.com/news/detail-714668.html
到了这里,关于Java调用HTTP接口的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!