Java 使用HttpURLConnection发送POST请求和Cookie

通常发送POST请求的地方是在浏览器的表单中.

可以通过脚本来自动化这个动作.

许多编程语言提供可以做到这一点, 比如Python, 另一门语言是Java.

下面的例子用HttpURLConnection发送POST请求以及数据和Cookie, 就像提交表单一样.

 
    public static void postContent(String title, String content) { 
        String url = "http://domain.com/api";
        URL verifiedurl = verifyUrl(url);
 
        try {
            if (url.toLowerCase().startsWith("https://")) {
                HostnameVerifier hv = new HostnameVerifier() {  
                    public boolean verify(String urlHostName, SSLSession session) {  
                        System.out.println("Warning: URL Host: " + urlHostName + " vs. "  
                                + session.getPeerHost());  
                        return true;  
                    }  
                };  
 
                try {
                    trustAllHttpsCertificates();
                } catch (Exception e) {
                    e.printStackTrace();
                }  
                HttpsURLConnection.setDefaultHostnameVerifier(hv);
            }
 
            HttpURLConnection con = (HttpURLConnection )verifiedurl.openConnection();
            con.setConnectTimeout(2000);
            con.setRequestProperty("User-Agent",
                                   "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2054.3 Safari/537.36");
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setRequestProperty("Cookie", "credential=value");
            Map<String,String> arguments = new HashMap<String,String>();
            arguments.put("description", "");
            arguments.put("keywords", "");
            arguments.put("cat", "");
            arguments.put("content", content);
            arguments.put("title", title);
            StringJoiner sj = new StringJoiner("&");
            for(Map.Entry<String,String> entry : arguments.entrySet())
                sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" 
                     + URLEncoder.encode(entry.getValue(), "UTF-8"));
            byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
            int length = out.length;
            con.setFixedLengthStreamingMode(length);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            con.connect();
 
            OutputStream os = con.getOutputStream();
            os.write(out);
 
            InputStream ins = con.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader( ins ,"UTF-8"));
            String line;
            StringBuffer pageBuffer  = new StringBuffer();
            char b[] = new char[100*1024];
            ArrayList<Integer> readedList = new ArrayList<Integer>();
            int readed;
 
            while((readed = reader.read(b)) != -1) {
                pageBuffer.append(String.copyValueOf(b,0,readed));
            }
            ins.close();
            reader.close();
            con.disconnect();
            String pagecontent = pageBuffer.toString();
            System.out.println(pagecontent);
        } catch (IOException e) {
 
            e.printStackTrace();
 
        }
    }
 
    public static URL verifyUrl( String url ){
        if ( !url.toLowerCase().startsWith("http://") && !url.toLowerCase().startsWith("https://"))
            return null;
 
        URL verifiedUrl = null;
        try {
            verifiedUrl = new URL(url);
        } catch ( Exception e ) {
            e.printStackTrace();
            return null;
        }
        return verifiedUrl;
    }
 
    private static void trustAllHttpsCertificates() throws Exception {  
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];  
        javax.net.ssl.TrustManager tm = new miTM();  
        trustAllCerts[0] = tm;  
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");  
        sc.init(null, trustAllCerts, null);  
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
    }  
 
    static class miTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager {  
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
            return null;  
        }  
 
        public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {  
            return true;  
        }  
 
        public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {  
            return true;  
        }  
 
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)throws java.security.cert.CertificateException {  
            return;  
        }  
 
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {  
            return;  
        }  
    }