java httpclient发送post请求
时间: 2023-11-03 20:05:12 浏览: 130
好的,下面是Java HttpClient发送POST请求的示例代码:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientExample {
public static void main(String[] args) {
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://www.example.com/api");
String requestBody = "{\"param1\": \"value1\", \"param2\": \"value2\"}";
StringEntity params = new StringEntity(requestBody);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
System.out.println(responseBody);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
```
在上面的代码中,我们首先创建了一个 HttpClient 对象。然后,我们创建了一个 HttpPost 对象,并设置了请求的 URL。接下来,我们设置了请求体,即要发送的数据。在这个例子中,我们使用 JSON 格式发送数据。接着,我们设置了请求头,指定了请求体的类型。最后,我们执行请求,并从响应中读取数据。注意,我们使用 HttpEntityUtils 工具类将响应实体转换为字符串。
阅读全文