fwq
2023-09-01 569daa38882b9382a70ee47ac068bdce5a736eb3
src/main/java/com/hx/util/RequestMethod.java
@@ -62,7 +62,7 @@
         conn.setDoOutput(true);//允许对外输出数据
         conn.setDoInput(true);
         conn.setUseCaches(false);
         conn.setRequestProperty("Charset", "utf-8");
         conn.setRequestProperty("Charset", encoding);
         conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
         //conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
         OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
@@ -76,6 +76,51 @@
      }
        return null;
    }
   /**
    * 发送Post请求
    * @param path 请求路径
    * @param content 发送内容
    * @param header 请求头参数设置
    * @param contentType 请求类型,默认application/x-www-form-urlencoded
    * @param encoding 编码,默认UTF-8
    * @return 服务器端内容
    */
   public static String sendPOSTRequest(String path, String content,Map<String,String> header,String contentType, String encoding){
      //byte[] entity = content.toString().getBytes();//生成实体数据
      try{
         if(StringUtils.isNull(contentType)){
            contentType = "application/x-www-form-urlencoded";
         }
         if(StringUtils.isNull(encoding)){
            encoding = "UTF-8";
         }
         HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
         conn.setConnectTimeout(5000);
         conn.setRequestMethod("POST");
         conn.setDoOutput(true);//允许对外输出数据
         conn.setDoInput(true);
         conn.setUseCaches(false);
         conn.setRequestProperty("Charset", encoding);
         conn.setRequestProperty("Content-Type",contentType);
         if(header != null){
            for(String key:header.keySet()){//keySet获取map集合key的集合  然后在遍历key即可
               conn.setRequestProperty(key,header.get(key));
            }
         }
         //conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
         OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
         outStream.write(content);
         outStream.flush();
         if(conn.getResponseCode() == 200){
            return StreamUtils.InputStreamTOString(conn.getInputStream());
         }
      }catch(Exception e){
         e.printStackTrace();
      }
      return null;
   }
   
   /**
    * 发送Post请求