JAVA 代码里HttpURLConnection post方式请求http服务

/**
     * post方式请求http服务
     * 
     * @param urlStr url地址
     * @param params 参数,例如:name=yxd&age=25
     * @return
     * @throws Exception
     */
    public static String _getURLByPost(String urlStr, String params) throws Exception {
        urlStr += "?" + params;

        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        System.out.println("=====访问的url:" + urlStr);
        System.out.println("=====访问的params:" + params);

        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.connect();// 连接

        PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
        printWriter.write(params);
        printWriter.flush();
        BufferedReader in = null;
        StringBuilder sb = new StringBuilder();

        try {
            int code = conn.getResponseCode();
            System.out.println("=====访问code" + code);
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String str = null;
            while ((str = in.readLine()) != null) {
                sb.append(str);
            }
        } catch (Exception ex) {
            throw ex;
        } finally {
            try {
                conn.disconnect();
                if (in != null) {
                    in.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException ex) {
                throw ex;
            }
        }
        return sb.toString();
    }

 

posted @ 2022-08-29 11:45  乡野小猫  阅读(56)  评论(0编辑  收藏  举报