HttpUtil工具示例(GET、POST请求)
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class HttpUtil {
public static String sendGet(String url, Map params, Map header) throws Exception {
HttpGet httpGet = null;
String body = "";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
List mapList = new ArrayList<>();
if (params != null) {
for (Entry entry : params.entrySet()) {
mapList.add(entry.getKey() + "=" + entry.getValue());
}
}
if (CollectionUtils.isNotEmpty(mapList)) {
url = url + "?";
String paramsStr = StringUtils.join(mapList, "&");
url = url + paramsStr;
}
httpGet = new HttpGet(url);
httpGet.setHeader("Content-type", "application/json; charset=utf-8");
httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
if (header != null) {
for (Entry entry : header.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
}
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("请求失败");
} else {
body = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
throw e;
} finally {
if (httpGet != null) {
httpGet.releaseConnection();
}
}
return body;
}
public static String sendPostJson(String url, String json, Map header) throws Exception {
HttpPost httpPost = null;
String body = "";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
if (header != null) {
for (Entry entry : header.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
StringEntity entity = new StringEntity(json, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("请求失败");
} else {
body = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
throw e;
} finally {
if (httpPost != null) {
httpPost.releaseConnection();
}
}
return body;
}
public static String sendPostForm(String url, Map params, Map header) throws Exception {
HttpPost httpPost = null;
String body = "";
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
if (header != null) {
for (Entry entry : header.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
List nvps = new ArrayList<>();
if (params != null) {
for (Entry entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("请求失败");
} else {
body = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
throw e;
} finally {
if (httpPost != null) {
httpPost.releaseConnection();
}
}
return body;
}
}
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class HttpAPIService {
@Autowired
private CloseableHttpClient httpClient;
@Autowired
private RequestConfig config;
/**
* 不带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
*
* @param url
* @return
* @throws Exception
*/
public String doGet(String url) throws Exception {
// 声明 http get 请求
HttpGet httpGet = new HttpGet(url);
// 装载配置信息
httpGet.setConfig(config);
// 发起请求
CloseableHttpResponse response = this.httpClient.execute(httpGet);
// 判断状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 返回响应体的内容
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
return null;
}
/**
* 带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
*
* @param url
* @return
* @throws Exception
*/
public String doGet(String url, Map map) throws Exception {
URIBuilder uriBuilder = new URIBuilder(url);
if (map != null) {
// 遍历map,拼接请求参数
for (Map.Entry entry : map.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
// 调用不带参数的get请求
return this.doGet(uriBuilder.build().toString());
}
/**
* 带参数的post请求
*
* @param url
* @param map
* @return
* @throws Exception
*/
public HttpResult doPost(String url, Map map) throws Exception {
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url);
// 加入配置信息
httpPost.setConfig(config);
// 判断map是否为空,不为空则进行遍历,封装from表单对象
if (map != null) {
List list = new ArrayList();
for (Map.Entry entry : map.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
// 构造from表单对象
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
// 把表单放到post里
httpPost.setEntity(urlEncodedFormEntity);
}
// 发起请求
CloseableHttpResponse response = this.httpClient.execute(httpPost);
return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
response.getEntity(), "UTF-8"));
}
/**
* 不带参数post请求
*
* @param url
* @return
* @throws Exception
*/
public HttpResult doPost(String url) throws Exception {
return this.doPost(url, null);
}
}
IP工具
public class IPUtil {
public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";
public static String getLocalHostIP() {
// 本地IP,如果没有配置外网IP则返回它
String localIp = null;
// 外网IP
String netIp = null;
try {
Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
// 是否找到外网IP
boolean finded = false;
while (netInterfaces.hasMoreElements() && ! finded) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = address.nextElement();
// 外网IP
if (! ip.isSiteLocalAddress() && ! ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == - 1) {
netIp = ip.getHostAddress();
finded = true;
break;
} else if (ip.isSiteLocalAddress() && ! ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == - 1) {
// 内网IP
localIp = ip.getHostAddress();
}
}
}
} catch (SocketException e) {
e.getMessage();
}
if (netIp != null && ! "".equals(netIp)) {
return netIp;
} else {
return localIp;
}
}
public static String getRemoteIp(HttpServletRequest request) {
// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址
String ip = getXForwardedForIp(request);
if (ipValid(ip)) {
return realIp(ip);
}
ip = request.getHeader("Proxy-Client-IP");
if (ipValid(ip)) {
return realIp(ip);
}
ip = request.getHeader("HTTP_CLIENT_IP");
if (ipValid(ip)) {
return realIp(ip);
}
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
if (ipValid(ip)) {
return realIp(ip);
}
ip = request.getRemoteAddr();
return realIp(ip);
}
private static String getXForwardedForIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
//ip 无效直接返回
if (! ipValid(ip)) {
return "";
}
if (ip.length() > 15) {
String[] ips = ip.split(",");
for (String strIp : ips) {
if (! ("unknown".equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
return ip;
}
return ip;
}
private static Boolean ipValid(String ip) {
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
return false;
}
return true;
}
private static String realIp(String ip) {
if (StringUtils.isEmpty(ip)) {
return "";
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
public static String getRemoteLocation(HttpServletRequest request) {
String ip = getRemoteIp(request);
return getIpLocation(ip);
}
public static String getIpLocation(String ip) {
String location = "未知";
if (StringUtils.isEmpty(ip)) {
return location;
}
Map param = new HashMap<>();
param.put("ip", ip);
try {
String rspStr = SmartHttpUtil.sendGet(IP_URL, param, null);
if (StringUtils.isEmpty(rspStr)) {
return location;
}
JSONObject jsonObject = JSON.parseObject(rspStr);
String data = jsonObject.getString("data");
JSONObject jsonData = JSON.parseObject(data);
String region = jsonData.getString("region");
String city = jsonData.getString("city");
location = region + " " + city;
if (location.contains("内网IP")) {
location = "内网(" + ip + ")";
}
} catch (Exception e) {
}
return location;
}
}
RequestTokenUtil
public class RequestTokenUtil {
private static final String USER_KEY = "smart_admin_user";
private static ThreadLocal RequestUserThreadLocal = new ThreadLocal();
public static void setUser(HttpServletRequest request, RequestTokenBO requestToken) {
request.setAttribute(USER_KEY, requestToken);
RequestUserThreadLocal.set(requestToken);
}
public static RequestTokenBO getThreadLocalUser() {
return RequestUserThreadLocal.get();
}
public static RequestTokenBO getRequestUser() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
if (request != null) {
return (RequestTokenBO) request.getAttribute(USER_KEY);
}
}
return null;
}
public static Long getRequestUserId() {
RequestTokenBO requestUser = getRequestUser();
if (null == requestUser) {
return null;
}
return requestUser.getRequestUserId();
}
}