springboot 调用http的post接口
时间: 2023-11-19 12:07:08 浏览: 140
SpringBoot使用httpclient发送Post请求时
在Spring Boot中,可以使用Java内置库或第三方库来调用HTTP的POST接口。
1. 使用Java内置库
可以使用Java内置库中的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) {
try {
URL url = new URL("http://example.com/api/post");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String data = "{\"message\":\"Hello, World!\"}";
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. 使用第三方库
可以使用第三方库如Apache HttpComponents或OkHttp来发送POST请求。示例代码如下:
使用Apache HttpComponents:
```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.util.EntityUtils;
public class HttpPostExample {
public static void main(String[] args) {
try {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("http://example.com/api/post");
StringEntity params = new StringEntity("{\"message\":\"Hello, World!\"}");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
```
使用OkHttp:
```java
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HttpPostExample {
public static void main(String[] args) {
try {
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create("{\"message\":\"Hello, World!\"}", MediaType.parse("application/json"));
Request request = new Request.Builder()
.url("http://example.com/api/post")
.post(body)
.build();
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
System.out.println(responseBody);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
```
以上是使用Java内置库和第三方库调用HTTP的POST接口的示例代码,你可以根据自己的需要选择其中一种方式来实现。
阅读全文