import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtil {
// 发送GET请求
public static String sendGet(String urlString) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 设置连接和读取超时时间
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
in.close();
} else {
System.out.println("GET request failed with response code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
// 发送POST请求
public static String sendPost(String urlString, String postData) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// 设置连接和读取超时时间
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 写入POST数据
try (OutputStream os = connection.getOutputStream()) {
byte[] input = postData.getBytes("utf-8");
os.write(input, 0, input.length);
}
// 获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
in.close();
} else {
System.out.println("POST request failed with response code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
}
sendGet 方法:用于发送 GET 请求。它接受一个 URL 字符串作为参数,并返回服务器响应的字符串。如果请求成功(HTTP 状态码为 200),则读取并返回响应内容;否则,输出错误信息。
sendPost 方法:用于发送 POST 请求。它接受两个参数:URL 字符串和要发送的 POST 数据。该方法将 POST 数据写入请求体中,并返回服务器的响应内容。同样地,如果请求成功,则读取并返回响应内容;否则,输出错误信息。
超时设置:为了防止请求长时间无响应,代码中设置了连接超时(5秒)和读取超时(5秒)。
异常处理:通过 try-catch 块捕获可能发生的异常,并打印堆栈信息以便调试。
上一篇:java正则表达式提取字符串
下一篇:java set 转 list
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站