java--Http请求发送json报文

Http请求发送json报文

  • 代码演示

代码演示

    /**
     * http
     * post 请求 发送json 报文
     */
    public static void send(PuKe puke){
        String url = "http://43.143.5.149:30020/api/v4/send";
        OutputStream outputStream = null;
        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = null;

        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
            //设置属性
            conn.setRequestProperty("Content-Type","application/json");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            //连接
            conn.connect();
            //将要传输的数据转成json 
            String jsonString = JSON.toJSONString(puke);
            if (jsonString != null){
                //传输数据
                outputStream = conn.getOutputStream();
                outputStream.write(jsonString.getBytes(StandardCharsets.UTF_8));
            }
            //拿到返回报文
            bis = new BufferedInputStream(conn.getInputStream());
            //接收报文
            bos = new ByteArrayOutputStream();
            int len = -1;
            byte[] bytes = new byte[1024];
            while ((len = bis.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }
            String s = bos.toString();
            //输出下返回报文,也可以拿到做别的处理,转成对象。
            System.out.println(s);

        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (outputStream != null){
                    outputStream.close();
                }
                if (bis != null){
                    bis.close();
                }
                if (bos != null){
                    bos.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

你可能感兴趣的:(面试,http,java,java,http,json,网络,服务器)