com.github.houbbbbb.sso.util.HttpClientUtil Maven / Gradle / Ivy
The newest version!
package com.github.houbbbbb.sso.util;
import com.github.houbbbbb.sso.cons.SSOPConstants;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.util.List;
/**
* @author : hbw
* @desctiption :
* @date : 2020-05-25 13:52
*/
public class HttpClientUtil {
public static String post(String url, PostParam postParam){
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
if(null != postParam) {
List nameValuePairList = postParam.getParam();
if (null != nameValuePairList && nameValuePairList.size() > 0) {
HttpEntity entity = new UrlEncodedFormEntity(nameValuePairList, SSOPConstants.SSO_UTF_8);
httpPost.setEntity(entity);
}
}
response = client.execute(httpPost);
if(200 == response.getStatusLine().getStatusCode()){
return EntityUtils.toString(response.getEntity(), SSOPConstants.SSO_UTF_8);
}
}catch (Exception e){
e.printStackTrace();
}finally{
if(null != response){
try{response.close();}catch (Exception e){e.printStackTrace();}
}
if(null != client){
try{client.close();}catch(Exception e){e.printStackTrace();}
}
}
return null;
}
}