java http操作相关工具类
2021/12/24 11:37:34
本文主要是介绍java http操作相关工具类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
导包
<!-- 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; /** * http操作相关工具类 * * @author ycs */ public class YcsHttpUtils { /** * 小项目使用默认配置即可 * <p> * 大项目需要专门配置链接数,链接池,超时重试...,详见:https://blog.csdn.net/w372426096/article/details/82713315 */ 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"; // IP地址查询 public static final String IP_URL = "https://searchplugin.csdn.net/api/v1/ip/get"; // 未知地址 public static final String UNKNOWN = "XX XX"; /** * 文件下载 * * @param url * @return */ 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); } } /** * 文件上传 * * @param url * @param file * @return */ 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); } } /** * 发送HttpGet请求 * * @param url * @param params 请求参数, 为null表示无参 * @return JSON字符串 */ 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); } } /** * 添加get请求参数 * * @param url * @param params * @return */ 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; } /** * 发送HttpPost请求 * * @param url * @param jsonStr 请求JSON字符串参数, 为null表示无参 * @return JSON字符串 */ 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); } } /** * 获取用户真实IP地址 * <p> * 不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址 * * @param request * @return */ public static String getRealClientIp(HttpServletRequest request) { //如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值 String ip = request.getHeader("X-Forwarded-For"); if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { // 多次反向代理后会有多个ip值,第一个ip才是真实ip if (ip.contains(",")) { ip = ip.split(",")[0]; } } //apache http做代理时一般会加上Proxy-Client-IP请求头 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } //apache http做代理时,weblogic插件加上WL-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"); } //nginx代理一般会加上此请求头 if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); } //当不使用代理获取的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); } } }
测试
/** * @author ycs */ 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")); // 文件下载 // byte[] entity = YcsHttpUtils.download("https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF"); // OutputStream outputStream = new FileOutputStream(desktopPath + "/entity.jpg"); // outputStream.write(entity); // outputStream.flush(); // outputStream.close(); // 文件上传 // InputStream inputStream = new FileInputStream("C:\\Users\\Tmind\\Desktop\\year.xlsx"); // byte[] file = new byte[inputStream.available()]; // inputStream.read(file); // String upload = YcsHttpUtils.upload("http://localhost:8080/testFile1", file, "text.xlsx"); // System.out.println(upload); // get请求 // Map<String, Object> params = new HashMap<>(); // params.put("id", 1); // String entity = YcsHttpUtils.sendGet("http://localhost:8080/test", params); // System.out.println(entity); // POST请求 // Map<String, Object> params = new HashMap<>(); // params.put("itemId", 123); // params.put("attrName", "attrName1"); // String jsonString = JSON.toJSONString(params); // String s = YcsHttpUtils.sendPost("http://localhost:8080/test", jsonString); // System.out.println(s); } }
这篇关于java http操作相关工具类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-04敏捷管理与看板工具:提升研发、设计、电商团队工作效率的利器
- 2025-01-04智慧养老管理工具如何重塑养老生态?
- 2025-01-04如何打造高绩效销售团队:工具与管理方法的结合
- 2025-01-04解决电商团队协作难题,在线文档工具助力高效沟通
- 2025-01-04春节超市管理工具:解锁高效运营与顾客满意度的双重密码
- 2025-01-046种主流销售预测模型:如何根据场景选用最佳方案
- 2025-01-04外贸服务透明化:增强客户信任与合作的最佳实践
- 2025-01-04重新定义电商团队协作:在线文档工具的战略作用
- 2025-01-04Easysearch Java SDK 2.0.x 使用指南(三)
- 2025-01-04百万架构师第八课:设计模式:设计模式容易混淆的几个对比|JavaGuide