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 @   乡野小猫  阅读(72)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
历史上的今天:
2018-08-29 easyui_validatebox常用验证
点击右上角即可分享
微信分享提示