java后端发起post请求
时间: 2023-07-29 22:06:44 浏览: 246
在Java后端发起POST请求,可以使用Java内置的HttpURLConnection类或第三方库如Apache HttpClient库。
使用HttpURLConnection类发起POST请求的示例代码如下:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpPostExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api/create";
String data = "param1=value1¶m2=value2";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为POST
con.setRequestMethod("POST");
// 设置请求头部信息
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 启用输出流,将请求参数写入请求体
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(data.getBytes());
os.flush();
os.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.toString());
}
}
```
使用Apache HttpClient库发起POST请求的示例代码如下:
```java
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpPostExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api/create";
String data = "{\"param1\":\"value1\",\"param2\":\"value2\"}";
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
// 设置请求头部信息
post.setHeader("Content-Type", "application/json");
// 设置请求体
StringEntity entity = new StringEntity(data);
post.setEntity(entity);
// 发送请求
HttpResponse response = client.execute(post);
// 获取返回结果
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String inputLine;
StringBuffer result = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
}
in.close();
// 打印返回结果
System.out.println(result.toString());
}
}
```
阅读全文