java发送post请求json格式
时间: 2023-05-01 18:01:38 浏览: 144
Java中可以使用第三方库如Apache HttpClient或者OkHttp来发送HTTP的POST请求,并在请求体中传输JSON数据。
举个例子,使用Apache HttpClient发送POST请求并传输JSON数据的代码如下:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://your-url");
String json = "{\"key\":\"value\"}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = httpClient.execute(httpPost);
```
同样的,使用OkHttp发送请求传输JSON数据的代码如下:
```java
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"key\":\"value\"}");
Request request = new Request.Builder()
.url("http://your-url")
.post(body)
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
```
在代码中可以看到,请求头Content-type和Accept都是设置为"application/json"的,这样服务端才知道客户端发送的数据是json格式的.
需要注意的是,在使用这些库发送请求时需要在项目中引入相应的依赖。
阅读全文