向服务器发送json格式的数据,并获得返回的数据

  1. 首先要有一个发送的地址
  2. 通过URL获取到连接
  3. 设置连接的参数
  4. 向连接发送数据
  5. 接收返回的数据
  public static void main(String[] args) throws IOException {
        //数据发送到哪里去
        String url = "https://wxcms-bg.ihxlife.com/selfmanage/xq/vnc/call/bind";

        /* 要发送的数据格式
        {"conTno": "",
        "payCount": "",
        "operatorCode": "470006464",
        "customerCode": "1500077993",
        "telA": "13800128000",
        "telB": "13800128001"}
         */
       //发送饿json数据 格式1 map
        Map<String, String> map = new HashMap<>();
        map.put("operatorCode", "123344");
        map.put("customerCode", "123344");
        map.put("telA", "15210896450");
        map.put("telB", "15210896466");
        //发送饿json数据 格式1 对象
        Mybean mybean = new Mybean();
        mybean.setCustomerCode("123344");
        mybean.setOperatorCode("123344");
        mybean.setTelA("15210896450");
        mybean.setTelB("15210896466");
      //  String jsonString = JSONObject.toJSONString(mybean);
        String jsonString = JSONObject.toJSONString(map);
        System.out.println("jsonString===>"+jsonString);

        //开始连接了
        URL murl = new URL(url);
        //跟地址建立连接
        HttpURLConnection conn=null;
        conn= (HttpURLConnection) murl.openConnection();
        conn.setConnectTimeout(6000);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Connection","Keep-Alive");
        conn.setRequestProperty("Charset","UTF-8");
        conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");
        conn.setRequestProperty("accept","application/json");
        byte[] bytes = jsonString.getBytes();
        conn.setRequestProperty("Content-Length",String.valueOf(bytes.length));

        //发送数据
        OutputStream outwrite = conn.getOutputStream();
        outwrite.write(bytes);
        outwrite.flush();
        outwrite.close();
        //接受返回的数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuilder  sb = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        conn.disconnect();
        //输出返回的数据
        System.out.println(sb.toString());
	    //解析返回的数据
        JSONObject jsonObject = JSON.parseObject(sb.toString());
        String o = (String) jsonObject.get("VirtualTel");
        System.out.println("VirtualTel===>"+o);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值