package org.bdware.sc.py.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpClient {
    public static String get(String ip, int port, String urlPath) {
        URL url;
        // 线程不安全
        StringBuilder sb = new StringBuilder();
        try {
            url = new URL("http://" + ip + ":" + port + urlPath);
            HttpURLConnection httpURLConnection;
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(2000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            httpURLConnection.connect();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8));
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
            }

            bufferedReader.close();
            httpURLConnection.disconnect();

            System.out.println(sb);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();

    }

    public static String post(String ip, int port, String urlPath, String jsonstr) {
        URL httpUrl;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            httpUrl = new URL("http://" + ip + ":" + port + urlPath);
            HttpURLConnection httpURLConnection;
            httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            httpURLConnection.connect();
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(jsonstr.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();

            BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line);
            }
            br.close();
            httpURLConnection.disconnect();

            System.out.println(stringBuilder);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


}