Java HttpRequest.post带参数例子
时间: 2024-10-25 12:10:33 浏览: 13
JAVA发送http get/post请求,调用http接口、方法详解
5星 · 资源好评率100%
在Java中,如果你想要使用`HttpURLConnection`或第三方库如Apache HttpClient发送POST请求并携带参数,你可以按照以下步骤操作:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api";
String requestBody = "key1=value1&key2=value2"; // 这里替换为你实际的参数字符串
try (BufferedReader reader = new BufferedReader(new StringReader(requestBody))) {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置连接属性
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 表示我们发送的是表单数据
con.setDoOutput(true); // 指定我们要写入输出流
// 发送数据
byte[] data = requestBody.getBytes(); // 转换参数为字节数组
con.getOutputStream().write(data);
// 获取响应
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
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.toString());
} else {
throw new RuntimeException("Failed : HTTP error code : " + responseCode);
}
}
}
}
```
阅读全文