您的位置:首页 > 理论基础 > 计算机网络

HttpClient发送Post请求(一)

2017-06-29 11:42 197 查看

pom

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>


code

package com.xxxxxx.xxxxx;

import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
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;

/**
* @author wushucheng
* @version 创建时间:2017年6月28日 下午5:20:23
* @TODO 类说明
*/
public class HttpUtil {

public static String post(String url, String body){

String result = null;
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(body, Charset.forName("UTF-8"));
httpPost.setEntity(stringEntity);
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(response != null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(client != null){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return result;
}

}


attention

以上代码可以发送 http/https post 请求

调用微信API的时候,若body存在中文,一定要进行 UTF-8 转码,否则会报错
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: