httpclient发送get请求参数为json
时间: 2023-11-16 20:15:24 浏览: 43
你可以使用以下代码使用 `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 格式,并将其添加到请求中。最后,我们发送请求并获取响应,将响应输出到控制台。