java发送get请求传json数据
时间: 2023-09-23 12:05:45 浏览: 304
使用java请求json接口数据
在Java中发送GET请求传递JSON数据,可以使用HttpClient库来实现。以下是一个示例代码:
```java
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGetWithEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class Main {
public static void main(String\[\] args) {
HttpClient httpClient = HttpClientBuilder.create().build();
String url = "http://example.com/api";
String json = "{\"key\":\"value\"}";
try {
HttpGetWithEntity httpGet = new HttpGetWithEntity(url);
httpGet.setEntity(new StringEntity(json));
HttpResponse response = httpClient.execute(httpGet);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们使用HttpClient库创建了一个HttpClient对象,并指定了请求的URL和JSON数据。然后,我们创建了一个HttpGetWithEntity对象,并将JSON数据设置为请求的实体。最后,我们执行GET请求并获取响应的内容。
请注意,这只是一个示例代码,你需要根据你的实际情况进行适当的修改。
#### 引用[.reference_title]
- *1* [java http get post 和 发送json数据请求](https://blog.csdn.net/somdip/article/details/130584038)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [java通过httpClient发送json格式数据请求(GET方式)](https://blog.csdn.net/xzj80927/article/details/127511924)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文