版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoyaoyulinger/article/details/77315694
使用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;
}
}