package org.bdware.sc.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpPostForm {
    public static void postForm(String url, Map<String, String> params) {
        String responseMessage;
        StringBuilder response = new StringBuilder();
        HttpURLConnection httpConnection = null;
        OutputStreamWriter out = null;
        BufferedReader reader;
        try {
            URL urlPost = new URL(url);
            httpConnection = (HttpURLConnection) urlPost.openConnection();
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
            httpConnection.setRequestMethod("POST");
            httpConnection.setUseCaches(false);
            httpConnection.setInstanceFollowRedirects(true);
            httpConnection.setRequestProperty("Connection", "Keep-Alive");
            httpConnection.setRequestProperty("Charset", "UTF-8");
            // 设置边界
            String BOUNDARY = "----------" + System.currentTimeMillis();
            // httpConnection.setRequestProperty("Content-Type", "multipart/form-data;
            // boundary=" + BOUNDARY);
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;boundary=" + BOUNDARY);

            // 连接，从postUrl.openConnection()至此的配置必须要在connect之前完成，
            // 要注意的是connection.getOutputStream会隐含的进行connect。
            // 实际上只是建立了一个与服务器的tcp连接，并没有实际发送http请求。

            httpConnection.connect();
            out = new OutputStreamWriter(httpConnection.getOutputStream(), StandardCharsets.UTF_8);

            StringBuilder sb = new StringBuilder();
            int count = params.size();
            for (String key : params.keySet()) {
                sb.append(key).append("=").append(URLEncoder.encode(params.get(key), "utf-8"));
                count--;
                if (count > 0) {
                    sb.append("&");
                }
            }
            out.write(sb.toString());
            System.out.println("send_url:" + url);
            System.out.println("send_data:" + sb);
            // flush and close
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
                if (null != httpConnection) {
                    httpConnection.disconnect();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        try {
            if (null == httpConnection) {
                throw new NullPointerException();
            }
            reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), StandardCharsets.UTF_8));
            while ((responseMessage = reader.readLine()) != null) {
                response.append(responseMessage);
                response.append("\n");
            }

            if (!"failure".equals(response.toString())) {
                System.out.println("success");
            } else {
                System.out.println("failure");
            }
            // 将该url的配置信息缓存起来
            System.out.println(response);
            System.out.println(httpConnection.getResponseCode());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
