package com.sport.sportcloudmarathonh5.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
/**
* @author zdj
* @version 1.0
* @date 2022-07-20 11:40:05
*/
public class HttpUtil {
private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
public static void main(String[] args) {
// if(judgeCurCityInTargetCity(getAddress("183.157.41.135"), "湖州")){
// System.out.println("在");
// } else {
// System.out.println("不在");
// }
Map<String, Object> body = new HashMap<String, Object>();
body.put("name", "杭");
body.put("type", 1);
body.put("phone", "13067730289");
body.put("venueKey", "wx1121112");
body.put("headImg", "https://cunjifen.oss-cn-beijing.aliyuncs.com/userImg/1608094265750.jpg");
JSONObject jsonObject = HttpUtil.sendPost("http://top.mohoo.club/api/faceRegister", JSON.toJSONString(body));
logger.info("请求第三方响应结果:" + jsonObject.toJSONString());
if (null != jsonObject) {
if (jsonObject.get("code") != null && jsonObject.getInteger("code") == 200) {
JSONObject data = jsonObject.getJSONObject("data");
Integer id = data.getInteger("id");
System.out.println(id);
}
}
}
/**
* 发送post请求
* 参数格式:json
* @param requestUrl 请求地址
* @param requestParam 请求参数
*/
public static JSONObject sendPost(String requestUrl, JSONObject requestParam){
JSONObject result = new JSONObject();
// 1. 创建HttpClient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 2. 创建HttpPost对象
HttpPost post = new HttpPost(requestUrl);
post.setEntity(new StringEntity(requestParam.toString(), HTTP.UTF_8)); // 这里这只字符格式,可以防止中文乱码
// 3. 执行请求并处理响应
try {
CloseableHttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
result = JSONObject.parseObject(EntityUtils.toString(entity));
}
response.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4. 释放资源
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
*/
public static JSONObject sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
JSONObject jsonObject = JSONObject.parseObject(result, JSONObject.class);
return jsonObject;
}
/**
* 发送get请求-原生请求返回
* @param requestUrl 请求地址
* @param requestParam 请求参数(有参数的情况下格式为:name='张三'&sex=13&adress='杭州市余杭区')
*/
public static JSONObject sendGet(String requestUrl, String requestParam){
JSONObject result = new JSONObject();
// 1. 创建HttpClient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 2. 创建HttpGet对象
HttpGet httpGet = new HttpGet(ObjectUtils.isEmpty(requestParam) ? requestUrl : (requestUrl +"?"+ requestParam));
// 3. 执行GET请求
try {
CloseableHttpResponse response = httpClient.execute(httpGet);
// 4. 获取响应实体
HttpEntity entity = response.getEntity();
// 5. 处理响应实体
if (entity != null) {
result = JSONObject.parseObject(EntityUtils.toString(entity));
}
response.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 6. 释放资源
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 发送get请求-将响应信息进行编码(utf-8)处理返回
* @param requestUrl 请求地址
* @param requestParam 请求参数(有参数的情况下格式为:name='张三'&sex=13&adress='杭州市余杭区')
*/
public static JSONObject sendGetEncode(String requestUrl, String requestParam) {
JSONObject result = new JSONObject();
requestUrl = ObjectUtils.isEmpty(requestParam) ? requestUrl : (requestUrl + "?" + requestParam);
// 3. 执行GET请求
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader in = null;
try {
// 建立连接
URL url = new URL(requestUrl);
urlConnection = (HttpURLConnection) url.openConnection();
// 将返回的输入流转换成字符串
inputStream = urlConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
in = new BufferedReader(inputStreamReader);
String jsonUserStr = in.readLine().toString();
result = JSONObject.parseObject(jsonUserStr);
} catch (IOException e) {
e.printStackTrace();
logger.error("发送请求异常:", e.getMessage());
} finally {
try {
if (in != null) {
in.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
if (urlConnection != null) {
urlConnection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
logger.error("关闭流出现:", e.getMessage());
}
}
return result;
}
/**
* 获取IP地址
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("获取ip地址异常:" + e);
}
//使用代理,则获取第一个IP地址
if(StringUtils.isEmpty(ip) ) {
if(ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
return ip;
}
/**
* 根据ip获取归属地
* @param ip
* @return
*/
public static String getAddress(String ip) {
URL url = HttpUtil.class.getClassLoader().getResource("ip2region.db");
File file;
if (url != null) {
file = new File(url.getFile());
} else {
return null;
}
if (!file.exists()) {
logger.error("Error: Invalid ip2region.db file, filePath:" + file.getPath());
return null;
}
//查询算法
int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
//DbSearcher.BINARY_ALGORITHM //Binary
//DbSearcher.MEMORY_ALGORITYM //Memory
try {
DbConfig config = new DbConfig();
DbSearcher searcher = new DbSearcher(config, file.getPath());
Method method;
switch (algorithm){
case DbSearcher.BTREE_ALGORITHM:
method = searcher.getClass().getMethod("btreeSearch", String.class);
break;
case DbSearcher.BINARY_ALGORITHM:
method = searcher.getClass().getMethod("binarySearch", String.class);
break;
case DbSearcher.MEMORY_ALGORITYM:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
default:
return null;
}
DataBlock dataBlock;
if (!Util.isIpAddress(ip)) {
logger.error("Error: Invalid ip address");
return null;
}
dataBlock = (DataBlock) method.invoke(searcher, ip);
return dataBlock.getRegion();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 判断当前ip的城市是否在指定的城市中
* @param curCity 当前ip城市数据
* @param targetCity 目标城市
* @return
*/
public static boolean judgeCurCityInTargetCity(String curCity, String targetCity) {
return curCity.contains(targetCity) ? true : false;
}
/**
* 获取请求体里面的body内容
**/
public static String readAsChars(HttpServletRequest request) throws UnsupportedEncodingException {
BufferedReader br = null;
StringBuilder sb = new StringBuilder("");
try
{
br = request.getReader();
String str;
while ((str = br.readLine()) != null)
{
sb.append(str);
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (null != br)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return sb.toString();
}
}
HttpUtil发送外部请求包工具类
于 2022-07-22 13:37:20 首次发布