StringrequestEntity httpClient4.5.14版本怎么写?
时间: 2024-09-12 20:01:55 浏览: 80
在Apache HttpClient 4.5.14版本中,处理HTTP请求通常会涉及到`HttpRequestEntity`的创建,特别是当需要发送POST、PUT等带实体的数据请求时。这里是一个基本的例子,展示如何使用`StringRequestEntity`:
```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 {
private static final CloseableHttpClient httpClient = HttpClients.createDefault();
public void sendPost(String url, String requestBody) throws Exception {
// 创建HttpPost请求
HttpPost httpPost = new HttpPost(url);
// 将字符串转换为StringRequestEntity
StringEntity stringEntity = new StringEntity(requestBody, "UTF-8");
stringEntity.setContentType("application/x-www-form-urlencoded"); // 设置Content-Type
// 设置请求体
httpPost.setEntity(stringEntity);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
System.out.println("Response status: " + statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseBody = EntityUtils.toString(entity, "UTF-8");
System.out.println("Response body: " + responseBody);
}
} else {
throw new RuntimeException("Failed to execute request, status code: " + statusCode);
}
}
}
// 关闭连接池
public void shutDown() throws IOException {
httpClient.close();
}
}
```
在这个例子中,你需要替换`url`和`requestBody`为你实际的URL和待发送的数据。当你完成操作后别忘了调用`shutDown()`关闭连接。
阅读全文