package chapter_14_solution;

import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpDemo {

    public static void main(String[] args) throws IOException {
        // 创建HttpURLConnection对象
        // http://123.56.60.184:8888/examine
        // http://123.56.60.184:8888/examRptPattern
        String url = "http://123.56.60.184:8888/examRptPattern";

        URL obj = new URL(url);
        // 打开连接
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求方法为POST
        con.setRequestMethod("POST");

        // 设置请求头
        con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        con.setRequestProperty("Accept", "application/json");

        // 设置请求体
        JSONObject jsonObject = new JSONObject();
        // 添加请求参数
        jsonObject.put("ExamClass", "彩超");
        jsonObject.put("ExamSubClass", "血管彩超");
        // 将JSON对象转换为字符串
        String jsonData = jsonObject.toString();
        // 将JSON数据转换为字节数组
        byte[] postDataJson = jsonData.getBytes(StandardCharsets.UTF_8);

        // 发送POST请求并获取返回数据
        con.setDoOutput(true);
        // 发送数据
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        // 写入数据
        wr.write(postDataJson);
        // 刷新数据
        wr.flush();
        // 关闭输出流
        wr.close();

        // 获取响应码
        int responseCode = con.getResponseCode();
        // 打印请求结果
        System.out.println("\n发送'POST'请求到: " + url);
        System.out.println("Post请求入参: " + jsonObject);
        System.out.println("出参: " + responseCode);

        // 读取服务器返回的数据
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        // 读取数据
        String inputLine;
        // 拼接数据
        StringBuilder response = new StringBuilder();

        // 读取数据
        while ((inputLine = in.readLine()) != null) {
            // 拼接数据
            response.append(inputLine);
        }
        // 关闭连接
        in.close();

        // 打印结果
        System.out.println(response.toString());

    }
}

