zoukankan      html  css  js  c++  java
  • Java后端发出post请求带参数并接收返回的json

    核心代码:

    参数格式:

    “key1=value1&key2=value2”

    /**
    *  sendUrl    (远程请求的URL)
    *  param    (远程请求参数)
    *  JSONObject    (远程请求返回的JSON)
    */
    private
    JSONObject sendPostUrl(String url, String param){ PrintWriter out = null; BufferedReader in = null; JSONObject jsonObject = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流(设置请求编码为UTF-8) out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 获取请求返回数据(设置返回数据编码为UTF-8) in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "UTF-8")); String line; while ((line = in.readLine()) != null) { result += line; } jsonObject = JSONObject.fromObject(result); System.out.println(jsonObject); } catch (IOException e) { e.printStackTrace(); } finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return jsonObject; }

    调用方法:

    public JSONObject send(String username, String password){
            String params = "username=" + username+ "&password=" + password;
            JSONObject jsonObject = sendPostUrl("https://www.ysy7.com/login/", params);
            return jsonObject;
        }
  • 相关阅读:
    数据库水平切分(拆库拆表)的实现原理解析(转)
    json序列化 & 反序列化
    数据库工作原理
    【原创】python多线程测试接口性能
    XML解析(DOM、ElementTree)及转换为JSON
    nginx+supervisor+gunicorn+flask
    3、爬取干货集中营的福利图片
    Python多环境扩展管理
    九、frp对外提供简单的文件访问服务
    八、frps服务端与nginx可共用80端口
  • 原文地址:https://www.cnblogs.com/klslb/p/7237728.html
Copyright © 2011-2022 走看看