java httpclient发送请求
时间: 2023-11-03 18:05:08 浏览: 95
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。
阅读全文