java后端发起post请求
时间: 2023-07-29 14:06:43 浏览: 96
Java后端发起POST请求可以使用Java提供的HttpURLConnection类或者第三方库如Apache的HttpClient等。
下面是使用HttpURLConnection类发起POST请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api/endpoint"; // 请求的URL
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头信息
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Content-Type", "application/json");
// 设置POST请求参数
String requestBody = "{\"key\": \"value\"}";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(requestBody);
wr.flush();
wr.close();
// 发起请求并获取响应
int responseCode = con.getResponseCode();
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 Code : " + responseCode);
System.out.println("Response : " + response.toString());
}
}
```
其中,必须设置请求方法为POST,设置Content-Type为application/json等需要根据实际情况进行调整。
另外,如果需要进行HTTPS请求,需要额外设置SSL证书验证等操作。
阅读全文
相关推荐

















