java httpclient发送post请求 带参数
时间: 2023-02-28 22:11:43 浏览: 155
JAVA通过HttpClient发送HTTP请求的方法示例
可以使用HttpClient类来发送带参数的POST请求。以下是一个简单的示例代码:
```
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) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api/post");
StringEntity entity = new StringEntity("param1=value1¶m2=value2");
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
System.out.println(EntityUtils.toString(responseEntity));
response.close();
httpClient.close();
}
}
```
在上面的代码中,我们创建了一个`CloseableHttpClient`对象,并使用`HttpPost`类来发送POST请求,请求地址为`http://example.com/api/post`。我们使用`StringEntity`类来封装请求参数,并通过设置请求头来告诉服务器请求内容的类型。最后,我们使用`CloseableHttpResponse`对象获取服务器的响应,并通过`EntityUtils.toString`方法将响应内容转换为字符串。
阅读全文