• Java实现发送HTTP的POST请求,返回数据以及请求状态


    /**
         * @param url:请求url
         * @param content: 请求体(参数)
         * @return errorStr:错误信息;status:状态码,response:返回数据
         */
        public Map<String, Object> request(String url, String content) {
            Map<String, Object> result = new HashMap<String, Object>();
            String errorStr = "";
            String status = "";
            String response = "";
            PrintWriter out = null;
            BufferedReader in = null;
            try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
                URLConnection conn = realUrl.openConnection();
                HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
                // 设置请求属性
                httpUrlConnection.setRequestProperty("Content-Type", "application/json");
                // 发送POST请求必须设置如下两行
                httpUrlConnection.setDoOutput(true);
                httpUrlConnection.setDoInput(true);
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(httpUrlConnection.getOutputStream());
                // 发送请求参数
                out.write(content);
                // flush输出流的缓冲
                out.flush();
                httpUrlConnection.connect();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    response += line;
                }
                status = new Integer(httpUrlConnection.getResponseCode()).toString();
            } catch (Exception e) {
                System.out.println("发送 POST 请求出现异常!" + e);
                errorStr = e.getMessage();
            }
            // 使用finally块来关闭输出流、输入流
            finally {
                try {
                    if (out != null) { out.close();}
                    if (in != null) {in.close();}
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
           
            result.put("errorStr", errorStr);
            result.put("response", response);
            result.put("status", status);
            return result;
    }
    

    原文地址:[一枚小程序员]https://blog.csdn.net/l347129991/article/details/73732925/

  • 相关阅读:
    golang中os/user包用法
    golang中os包用法
    与table有关的布局
    jQuery 从 1.9 版开始,移除了 $.browser 和 $.browser.version
    canvas里调用getImageData的报security的问题
    CSS样式覆盖规则
    windows7文件夹怎样默认图片大图显示?
    Jboss,Tomcat 远程调试配置
    IE(IE6/IE7/IE8)支持HTML5标签
    JS 继承(类式 与 原型式)
  • 原文地址:https://www.cnblogs.com/aixing/p/13327484.html
Copyright © 2020-2023  润新知