httpclient发送post请求并传送txt数据的工具类
时间: 2024-05-16 15:20:01 浏览: 12
以下是使用 Apache HttpClient 发送 POST 请求并传递 txt 数据的 Java 工具类示例:
```java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
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.util.EntityUtils;
public class HttpClientUtil {
public static String sendPost(String url, String text) throws IOException {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(url);
HttpEntity entity = EntityBuilder.create().setText(text).build();
httpPost.setEntity(entity);
try (CloseableHttpResponse response = client.execute(httpPost)) {
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
}
}
}
return null;
}
}
```
其中 `url` 为请求地址,`text` 为要传递的文本数据。调用示例:
```java
String response = HttpClientUtil.sendPost("http://example.com/api", "Hello, World!");
```
注意:发送请求时需要处理可能抛出的 `IOException` 异常。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)