HttpClient 发送get请求并返回Json数据

69 篇文章 232 订阅 ¥99.90 ¥299.90
本文通过实例讲解了如何利用HttpClient发送GET请求,以调用百度百科接口获取JSON数据。步骤包括:首先介绍了一个API请求示例,然后展示了具体的代码实现,最后给出了运行后的结果。
摘要由CSDN通过智能技术生成
你可以使用以下代码使用 `httpclient` 发送 GET 请求参数为 JSON: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URI; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONObject; public class HttpClientGetWithJson { public static void main(String[] args) { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(); // 设置请求头 getRequest.addHeader("accept", "application/json"); getRequest.addHeader("Content-Type", "application/json"); // 构造请求参数为JSON格式 JSONObject json = new JSONObject(); json.put("key1", "value1"); json.put("key2", "value2"); StringEntity entity = new StringEntity(json.toString()); // 设置请求参数 getRequest.setURI(new URI("http://example.com/api/endpoint?" + entity)); getRequest.setEntity(entity); // 发送请求并获取响应 HttpResponse response = httpClient.execute(getRequest); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; while ((output = br.readLine()) != null) { System.out.println(output); } httpClient.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们首先创建了一个 `DefaultHttpClient` 实例,然后创建一个 GET 请求并设置请求头。接下来,我们将请求参数构造为 JSON 格式,并将其添加到请求中。最后,我们发送请求并获取响应,将响应输出到控制台。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值