由于开发的时候用到了,所以也整理了一下,具体代码如下:
/**
* @Title: httpGetRequest
* @Description: httpGet请求
* @param url
* @return
* @throws ParseException
* @throws IOException
*/
public static String httpGetRequest(String url) throws ParseException,
IOException
{
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
String retStr = "";
HttpResponse response = client.execute(httpGet);
retStr = EntityUtils.toString(response.getEntity(), "UTF-8");
logger.info("报文接收时间:" + DateUtil.getCurrentDateTime());
logger.info("接收内容:" + retStr);
return retStr;
}
/**
* @Title: httpGetRequest
* @Description: post请求
* @param url
* @return
* @throws ParseException
* @throws IOException
*/
public static String httpPostRequest(String url, String reqData)
throws ParseException, IOException
{
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
String retStr = "";
StringEntity re = new StringEntity(reqData, "UTF-8");
// httpPost.setHeader("Content-Type", "application/xml; charset=UTF-8");
httpPost.setEntity(re);
HttpResponse response = client.execute(httpPost);
retStr = EntityUtils.toString(response.getEntity(), "UTF-8");
return retStr;
}
至此,该工具类结束,顺便说一下上面引入的jar文件,如下:
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpGet;
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;