http调研post工具类方法企业版代码
时间: 2023-11-12 09:06:38 浏览: 33
以下是Java中使用HttpClient发送HTTP 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 HttpUtil {
public static String doPost(String url, String json) throws IOException {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(json, "UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity, "UTF-8");
return result;
}
}
```
在上述代码中,需要修改的内容包括请求URL、请求参数、请求头等信息,以及处理API服务器返回结果的方式。
注意:使用HttpClient发送HTTP请求需要导入Apache HttpClient的Jar包。如果使用Maven,则需要在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
```