HttpURLConnection 发送请求
程序员文章站
2022-07-08 16:02:27
public class HttpURLConnectionUtil { public static String sendHttpRequest(String httpUrl, Map params) throws IOException { //1.建立URL连接对象 URL url = new URL(httpUrl); //2.创建连接 H....
public class HttpURLConnectionUtil { public static String sendHttpRequest(String httpUrl, Map<String, String> params) throws IOException { //1.建立URL连接对象 URL url = new URL(httpUrl); //2.创建连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //3.设置请求方式 conn.setRequestMethod("POST"); //是否需要输出 conn.setDoOutput(true); if(!CollectionUtils.isEmpty(params)){ //拼接参数 StringBuilder sb = new StringBuilder(); for(Map.Entry<String, String> param : params.entrySet()){ sb.append("&").append(param.getKey()).append("=").append(param.getValue()); } conn.getOutputStream().write(sb.substring(1).toString().getBytes("UTF-8")); } conn.connect(); String responseStr = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("UTF-8")); return responseStr; } public static void main(String[] args) throws IOException { Map<String, String> params = new HashMap<>(); String str = HttpURLConnectionUtil.sendHttpRequest("",params); System.out.println(str); } }
本文地址:https://blog.csdn.net/xiaoxiamiqianqian/article/details/110282861
上一篇: Vue 异步请求一 登录