java如何接受curl -H "Content-Type: application/json" -X POST -d '{"user_id": "123", "coin":100, "success":1, "msg":"OK!" }'中-d中的POST内容
时间: 2023-10-04 08:12:08 浏览: 97
curl-7.46.0-win64.ext
在Java中,可以使用Apache HttpClient库来发送HTTP请求,并接收cURL命令中-d参数的POST内容。以下是示例代码:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class CurlToJava {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost("http://example.com/api/endpoint");
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 设置请求体
String jsonBody = "{\"user_id\": \"123\", \"coin\":100, \"success\":1, \"msg\":\"OK!\" }";
StringEntity entity = new StringEntity(jsonBody);
httpPost.setEntity(entity);
// 发送请求
HttpResponse response = httpClient.execute(httpPost);
// 获取响应内容
HttpEntity responseEntity = response.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
System.out.println(responseBody);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
在上述代码中,我们创建了一个HttpPost对象,并设置了请求URL、请求头和请求体。通过执行`httpClient.execute(httpPost)`方法发送请求并获取响应。最后,我们将响应内容转换为字符串并进行处理。
阅读全文