Java发送Https post请求(已封装,可直接用)

时间:2025-03-17 18:58:09
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .X509Certificate;

import ;
import ;
import ;
import ;
import ;
import .X509TrustManager;

public class HttpUtil
{
    public static String doPostToJson(String urlPath, String Json) {

        String result = "";
        BufferedReader reader = null;
        HttpURLConnection conn = null;
        try {
            trustAllHosts();
            URL url = new URL(urlPath);
            if (().toLowerCase().equals("https")) {
                HttpsURLConnection httpsConn = (HttpsURLConnection) ();
                (DO_NOT_VERIFY);
                conn = httpsConn;
            }
            else {
                conn = (HttpURLConnection) ();
            }

            ("POST");
            (true);
            (true);
            (false);
            ("Connection", "Keep-Alive");
            ("Charset", "UTF-8");
            ("Content-Type", "application/json; charset=UTF-8");
            // ("accept","*/*");
            ("accept", "application/json");
            if (Json != null) {
                byte[] writebytes = ();
                ("Content-Length", ());
                OutputStream outwritestream = ();
                (());
                ();
                ();
            }

            if (() == 200) {
                reader = new BufferedReader(new InputStreamReader((), "utf-8"));
                result = ();
            }
        }
        catch (Exception e) {
            ();
        }
        finally {
            if (reader != null) {
                try {
                    ();
                }
                catch (IOException e) {
                    ();
                }
            }
        }
        return result;
    }

    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier()
    {
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    };

    public static void trustAllHosts() {
        TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager()
        {

            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[] {};
            }

            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

            }

            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

            }
        }

        };

        try {
            SSLContext sc = ("TLS");
            (null, trustAllCerts, new SecureRandom());
            (());
        }
        catch (Exception e) {
            ();
        }

    }

}