Java HttpURLConnection Send POST request with Cookie

Send POST request usually involves filling HTML form and submitting through your browser.

To automate this action you may need to do it in a script.

Many programming languages can do this, Python would be very handy, another choice would be Java if it's your working language.

The following example uses HttpURLConnection to send POST request with cookie and data just like a form submit, it also output any response from the request.

 
    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;  
        }  
    }