Java 发送 POST 请求示例 - 使用 HttpURLConnection
以下是一个使用 Java 发送 POST 请求的例子:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class HttpPostExample {
public static void main(String[] args) throws Exception {
String url = 'http://example.com/api/post';
Map<String, String> params = new HashMap<>();
params.put('param1', 'value1');
params.put('param2', 'value2');
// 创建连接
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 添加请求头
con.setRequestMethod('POST');
con.setRequestProperty('User-Agent', 'Mozilla/5.0');
con.setRequestProperty('Accept-Language', 'en-US,en;q=0.5');
// 添加请求参数
String urlParameters = '';
for (Map.Entry<String, String> entry : params.entrySet()) {
if (!urlParameters.isEmpty()) {
urlParameters += '&';
}
urlParameters += entry.getKey() + '=' + entry.getValue();
}
// 发送POST请求
con.setDoOutput(true);
con.getOutputStream().write(urlParameters.getBytes('UTF-8'));
// 获取响应结果
int responseCode = con.getResponseCode();
System.out.println('Sending POST request to URL: ' + url);
System.out.println('Post parameters: ' + urlParameters);
System.out.println('Response Code: ' + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应结果
System.out.println('Response: ' + response.toString());
}
}
在这个例子中,我们发送了一个 POST 请求到 http://example.com/api/post,并传递了两个参数:param1 和 param2。我们使用 HttpURLConnection 类来发送请求,设置请求头和请求参数,然后获取响应结果。最后,我们打印出响应结果。
原文地址: https://www.cveoy.top/t/topic/mlwR 著作权归作者所有。请勿转载和采集!