Http请求辅助工具HttpClient

来源:互联网 发布:创维电视连接有线网络 编辑:程序博客网 时间:2024/05/16 04:48

/**

 * @功能描述:http请求辅助工具

 */

@Component

public class HttpUtil{

privateLog logger = LogFactory.getLog(getClass());// 日志

 

/**

 * @功能描述:http执行get方法

 */

publicString get(String url) {

Stringtext = "";

HttpClientclient = HttpClients.createDefault();

HttpGetget = new HttpGet("http://localhost:8080" + url); 

HttpResponseresponse;

try{

response= client.execute(get);

HttpEntityentity = response.getEntity();

text= EntityUtils.toString(entity);

}catch (ClientProtocolException e) {

logger.error("http执行get请求出现ClientProtocolException异常");

e.printStackTrace();

}catch (IOException e) {

logger.error("http执行get请求出现IOException异常");

e.printStackTrace();

}finally {

get.releaseConnection();//释放连接

}

returntext;

}

 

/**

 * @功能描述:http执行post方法

 */

publicString post(String url, Map<String, String> map) {

Stringtext = "";

HttpClientclient = HttpClients.createDefault();

HttpPostpost = new HttpPost("http://localhost:8080" + url);

try{

List<NameValuePair>params = new ArrayList<>();// 定义名值对类型的list

for(Map.Entry<String, String> entry : map.entrySet()) {

params.add(newBasicNameValuePair(entry.getKey(), entry.getValue()));

}

HttpEntityhttpEntity = new UrlEncodedFormEntity(params, "utf-8");//参数重新编码并放到请求实体中

post.setEntity(httpEntity);//把请求实体放到post请求中

HttpResponseresponse = client.execute(post);

HttpEntityentity = response.getEntity();

text= EntityUtils.toString(entity);

}catch (ClientProtocolException e) {

logger.error("http执行get请求出现ClientProtocolException异常");

e.printStackTrace();

}catch (IOException e) {

logger.error("http执行get请求出现IOException异常");

e.printStackTrace();

}finally {

post.releaseConnection();//释放连接

}

returntext;

}

}


0 0
原创粉丝点击