java httpclient get请求
时间: 2023-05-01 13:03:38 浏览: 111
Java HttpClient是一个用于发送HTTP请求的工具,可以发送GET请求、POST请求等等。其中,GET请求是一种请求方法,用于获取服务器上的资源或数据。通过Java HttpClient发送GET请求,可以让Java程序模拟浏览器发送HTTP请求,获取服务器上的数据信息。
相关问题
java HttpClient get请求返回值输出JSON
可以使用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`并将其输出到控制台。最后,我们将实体内容消耗掉,以便可以重复使用连接。
java httpclient发送请求
Java HttpClient是一个发送HTTP请求的开源库,可以用来发送GET、POST等请求。下面是使用HttpClient发送POST请求的示例代码:
```java
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost("http://example.com/api/endpoint");
httpPost.addHeader("Content-Type", "application/json");
String jsonData = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
StringEntity entity = new StringEntity(jsonData);
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
HttpEntity responseEntity = response.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
System.out.println(responseBody);
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace(); }
}
}
}
```
以上代码使用了Apache HttpClient库,它需要引入相关的jar包。首先创建一个CloseableHttpClient对象,然后创建一个HttpPost对象,并设置请求URL和请求头部信息。接着创建一个StringEntity对象,将请求参数转化为JSON格式,并将其设置为HttpPost的实体。最后执行HttpPost请求,获取响应实体,将其转化为字符串并打印出来。最后关闭HttpClient。
阅读全文