HttpPost 类是 Apache HttpClient 库中的一个类,用于构建 HTTP POST 请求。以下是 HttpPost 类的一些常用方法和代码案例:
常用方法
-
构造方法:
HttpPost(String uri)
:创建一个HttpPost
对象,并将请求的 URI 作为参数传递。
-
设置请求体:
setEntity(HttpEntity entity)
:设置 POST 请求的请求体。
-
添加请求头:
addHeader(String name, String value)
:向请求中添加一个头信息。setHeaders(Header[] headers)
:设置请求的所有头信息。
-
配置请求参数:
setConfig(RequestConfig config)
:设置请求的配置,如超时时间等。
代码案例
案例 1:使用 HttpPost
发送一个简单的 POST 请求。
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api");
try {
HttpResponse response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
System.out.println(responseString);
} finally {
httpClient.close();
}
在这个例子中,我们创建了一个 HttpPost
对象,并使用 httpClient
执行了请求。响应内容被转换成字符串并打印出来。
案例 2:使用 HttpPost
发送一个包含 JSON 数据的 POST 请求。
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.HttpResponse;
import org.apache.http.util.EntityUtils;
String json = "{\"key\":\"value\"}";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setEntity(new StringEntity(json, "UTF-8"));
try {
HttpResponse response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
System.out.println(responseString);
} finally {
httpClient.close();
}
在这个例子中,我们创建了一个包含 JSON 数据的 StringEntity
,并将其设置为 HttpPost
对象的请求体。我们还设置了内容类型为 application/json
。
案例 3:使用 HttpPost
发送一个包含表单数据的 POST 请求。
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://example.com/api");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("field1", new StringBody("value1"));
builder.addPart("field2", new StringBody("value2"));
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
try {
HttpResponse response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
System.out.println(responseString);
} finally {
httpClient.close();
}