ChenJiaHe
2021-01-29 81d5034c41d6391e9a139c8be8829d8b469128f2
新增请求方法
1个文件已修改
47 ■■■■■ 已修改文件
src/main/java/com/hx/util/RequestMethod.java 47 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
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");
@@ -80,6 +80,51 @@
    /**
     * 发送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请求
     * @param path 请求路径
     * @param entity 发送内容
     * @param encoding 编码
     * @return 服务器端内容