用java封装一个 http请求的工具类
以下是一个简单的 Java 封装 HTTP 请求的工具类示例:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtils {
public static String sendGet(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
这个工具类只提供了一个 sendGet 方法,用于发送 GET 请求并返回响应内容。在方法中,我们首先将 URL 转换为 URL 对象,并打开一个 HttpURLConnection 连接。然后设置请求方法为 GET,并设置 User-Agent 请求头。接下来,我们从连接的输入流中读取响应内容,并将其添加到字符串缓冲区中。最后,我们关闭输入流并返回响应内容字符串。
使用时,我们只需要传递一个 URL 参数给 sendGet 方法即可,例如:
String response = HttpUtils.sendGet("https://www.baidu.com");
System.out.println(response);
该代码将向百度发送 GET 请求并打印响应内容。
原文地址: https://www.cveoy.top/t/topic/Yuf 著作权归作者所有。请勿转载和采集!