import java.io.BufferedReader;
import java.io.InputStreamReader;
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 reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.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 param) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true); // 启用输出流
// 设置请求头
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 设置连接超时时间和读取超时时间
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 写入POST参数
byte[] postData = param.getBytes("UTF-8");
connection.getOutputStream().write(postData);
// 获取响应码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
} else {
System.out.println("POST request failed with response code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
public static void main(String[] args) {
// 示例:发送GET请求
String getResponse = sendGet("http://example.com/api/get");
System.out.println("GET Response: " + getResponse);
// 示例:发送POST请求
String postResponse = sendPost("http://example.com/api/post", "param1=value1¶m2=value2");
System.out.println("POST Response: " + postResponse);
}
}
sendGet 方法:用于发送 HTTP GET 请求。它接收一个 URL 字符串作为参数,并返回服务器的响应内容。如果响应码为 200(HTTP_OK),则读取并返回响应内容;否则,打印错误信息。
sendPost 方法:用于发送 HTTP POST 请求。它接收一个 URL 字符串和一个参数字符串作为参数,并返回服务器的响应内容。设置请求头为 application/x-www-form-urlencoded,并将参数写入输出流。如果响应码为 200,则读取并返回响应内容;否则,打印错误信息。
main 方法:包含两个示例调用,分别演示如何使用 sendGet 和 sendPost 方法发送 HTTP 请求,并打印响应结果。
希望这段代码对你有帮助!
下一篇:java bean是什么
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站