java HttpClient get请求返回值输出JSON
时间: 2024-01-31 17:02:58 浏览: 33
可以使用HttpClient发送GET请求获取JSON数据,并将其输出到控制台。以下是一个示例代码:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet();
request.setURI(new URI("https://jsonplaceholder.typicode.com/todos/1"));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
JSONObject jsonObject = new JSONObject(result.toString());
System.out.println(jsonObject.toString());
EntityUtils.consume(response.getEntity());
}
}
```
此代码将向`https://jsonplaceholder.typicode.com/todos/1`发送GET请求,并将返回的JSON数据输出到控制台。请注意,我们创建了一个`HttpClient`实例并使用它来执行请求。在响应中,我们读取实体内容并将其转换为字符串。然后,我们将字符串转换为`JSONObject`并将其输出到控制台。最后,我们将实体内容消耗掉,以便可以重复使用连接。