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

HttpUtil工具类发送post请求

2017-08-17 10:55 423 查看
使用apache的HttpClient发送post请求。

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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 HttpUtil {

private static String charset = "utf-8";

public static String postMethod(String url, String json) throws ClientProtocolException, IOException{
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();

StringEntity entity = new StringEntity(json, charset);//解决中文乱码问题
entity.setContentEncoding(charset);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);

if(response.getStatusLine().getStatusCode() == 200){
HttpEntity httpEntity = response.getEntity();
return EntityUtils.toString(httpEntity, charset);
}
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java HttpClient post