怎么使用httpclient发送post的get请求
时间: 2023-05-30 12:02:10 浏览: 161
HttpClient是一个开源的轻量级HTTP客户端库,可以用来发送HTTP请求。
使用HttpClient发送GET请求:
```java
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://www.example.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
```
使用HttpClient发送POST请求:
```java
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://www.example.com");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "test"));
params.add(new BasicNameValuePair("password", "123456"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
```
以上示例中,我们首先创建了一个HttpClient对象,然后使用HttpGet或HttpPost对象来设置请求URL和请求参数,最后使用execute方法来发送请求并获取响应。在POST请求中,我们使用了NameValuePair来设置请求参数,然后使用UrlEncodedFormEntity将参数编码后设置到HttpPost对象中的Entity中。
阅读全文