导包
<!-- apache http请求组件 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.9</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.9</version>
</dependency>
工具类
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
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.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.assertj.core.util.Maps;
import com.alibaba.fastjson.JSONObject;
public class YcsHttpUtils {
private static final CloseableHttpClient httpclient = HttpClients.createDefault();
private static final String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36";
public static final String IP_URL = "https://searchplugin.csdn.net/api/v1/ip/get";
public static final String UNKNOWN = "XX XX";
public static byte[] download(String url) {
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("User-Agent", userAgent);
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
return EntityUtils.toByteArray(response.getEntity());
} catch (Exception e) {
throw new RuntimeException("文件下载失败!url = " + url + "\n" + e);
}
}
public static String upload(String url, byte[] file, String fileName) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("User-Agent", userAgent);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody byteArrayBody = new ByteArrayBody(file, fileName);
builder.addPart("file", byteArrayBody);
httpPost.setEntity(builder.build());
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
return EntityUtils.toString(response.getEntity());
} catch (Exception e) {
throw new RuntimeException("文件上传失败!url = " + url + "\n" + e);
}
}
public static String sendGet(String url, Map<String, Object> params) {
url = appendParams(url, params);
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("User-Agent", userAgent);
httpGet.setHeader("Accept-Charset", Consts.UTF_8.name());
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
return EntityUtils.toString(response.getEntity());
} catch (Exception e) {
throw new RuntimeException("发送HttpGet请求失败!url = " + url + "\n" + e);
}
}
private static String appendParams(String url, Map<String, Object> params) {
if (null != params && params.size() > 0) {
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : params.keySet()) {
if (i == 0) {
param.append("?");
} else {
param.append("&");
}
param.append(key).append("=").append(params.get(key));
i++;
}
url += param;
}
return url;
}
public static String sendPost(String url, String jsonStr) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("User-Agent", userAgent);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
if (null != jsonStr) {
StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);
httpPost.setEntity(entity);
}
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
return EntityUtils.toString(response.getEntity());
} catch (Exception e) {
throw new RuntimeException("发送HttpPost请求失败!url = " + url + "\n" + e);
}
}
public static String getRealClientIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
if (ip.contains(",")) {
ip = ip.split(",")[0];
}
}
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.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
String hostAddress = "127.0.0.1";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException("获取用户ip失败!");
}
return ip.equals("0:0:0:0:0:0:0:1") ? hostAddress : ip;
}
public static String getRealAddressByIP(String ip) {
if ("127.0.0.1".equals(ip)) {
return "内网IP";
}
try {
String rspStr = sendGet(IP_URL, Maps.newHashMap("ip", ip));
if (StringUtils.isBlank(rspStr)) {
return UNKNOWN;
}
JSONObject obj = JSONObject.parseObject(rspStr);
String data = obj.getString("data");
JSONObject address = JSONObject.parseObject(data);
return (String) address.get("address");
} catch (Exception e) {
throw new RuntimeException("获取地理位置失败!ip = " + ip);
}
}
}
测试
public class SelfTest {
private File desktopDir;
private String desktopPath;
@Before
public void desktopDirTest() {
desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
desktopPath = desktopDir.getAbsolutePath();
}
@Test
public void HttpUtils() throws Exception {
System.out.println(YcsHttpUtils.getRealAddressByIP("115.192.212.206"));
}
}