http的get post 请求工具类
HttpClientUtil
package com.angular.base.util.httpUtil;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/*
* 执行http请求的java方法 下面提供GET 和 POST 请求 参数是以Map形式和jSON的格式
*
* */
public class HttpClientUtil {
/**
* 获取HttpServletRequest;
*
* @return [参数说明]
*
* @return HttpServletRequest [返回类型说明]
* @exception throws
* [违例类型] [违例说明]
* @see [类、类#方法、类#成员]
*/
public static HttpServletRequest getHttpRequest()
{
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
/**
* 返回用户的IP地址
*
* @param request
* @return
*/
public static String toIpAddr(HttpServletRequest request)
{
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getRemoteAddr();
}
return ip;
}
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
//post请求 请求的url content请求体 contentType 请求体类型 --ContentType.APPLICATION_JSON -ContentType.APPLICATION_XML
public static String doPost(String url,String content,String contentType) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 模拟表单
StringEntity entity = new StringEntity(content,contentType);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
}
HttpParam :
package com.angular.base.util.httpUtil; /* * http请求参数的封装类 * @Author:方伟林 * @Time:2016/12/27 * */ public class HttpParam { private String key; // 请求参数 private String value; // 参数值 public HttpParam() {} public HttpParam(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
HttpParamOperation :
package com.angular.base.util.httpUtil; import java.net.URLEncoder; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; /* * http请求参数的格式化、下面提供了两种方法 一个map 还有一个是基于httpParam类 * @Author:方伟林 * @Time:2016/12/27 * */ public class HttpParamOperation { private HttpParamOperation() {} private static Logger logger = Logger.getLogger(HttpParamOperation.class.getName()); /** * Created by fangweilin on 16/12/27 * @use 将map转换成url参数格式: name1=value1&name2=value2 * @param map 参数map * @return String 返回参数格式: name1=value1&name2=value2 */ public static String getUrlParamsFromMap(Map<String, String> map) throws Exception { try { if (null != map) { StringBuilder stringBuilder = new StringBuilder(); for (Map.Entry<String, String> entry : map.entrySet()) { stringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=") .append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&"); } String content = stringBuilder.toString(); if (content.endsWith("&")) { content = StringUtils.substringBeforeLast(content, "&"); } return content; } } catch (Exception e) { logger.error(e); } return null; } /** * Created by fangweilin on 16/12/27 * @use 将HttpParam列表转换成url参数格式: name1=value1&name2=value2 * @param httpParamList HttpParam列表 * @return String 返回参数格式: name1=value1&name2=value2 */ public static String getUrlParamsFromList(List<HttpParam> httpParamList) throws Exception { try { if (null != httpParamList) { StringBuilder stringBuilder = new StringBuilder(); if (httpParamList.size() > 0) { for (HttpParam httpParam : httpParamList) { stringBuilder.append(URLEncoder.encode(httpParam.getKey(), "UTF-8")).append("=") .append(URLEncoder.encode(httpParam.getValue(), "UTF-8")).append("&"); } String content = stringBuilder.toString(); if (content.endsWith("&")) { content = StringUtils.substringBeforeLast(content, "&"); } return content; } } } catch (Exception e) { logger.error(e); } return null; }
}