Java如何调用HTTP接口
更新时间:2025年01月26日 09:17:45 作者:荒·湮
本文介绍了Java调用HTTP接口的方法,包括使用HttpURLConnection和HttpClient工具,作者分享了个人经验,并鼓励读者参考和支持
Java调用HTTP接口
说明
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();
// 设置请求方法为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());
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Java实现将txt/word/pdf转成图片并在线预览的功能
本文将基于aspose-words(用于txt、word转图片),pdfbox(用于pdf转图片),封装成一个工具类来实现txt、word、pdf等文件转图片的需求并实现在线预览功能,需要的可以参考一下2023-05-05
Spring容器-BeanFactory和ApplicationContext使用详解
这篇文章主要为大家介绍了Spring容器-BeanFactory和ApplicationContext的使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-04-04


最新评论