Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
    public static int timeout = 1000 * 10;

    public static String getPosthtml(String posturl, String postData, String encode) {

        String html = "";
        URL url;
        try {
            url = new URL(posturl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("User-Agent", userAgent);

            String postDataStr = postData;
            byte[] bytes = postDataStr.getBytes("utf-8");
            connection.setRequestProperty("Content-Length", "" + bytes.length);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Cache-Control", "no-cache");
            connection.setDoOutput(true);
            connection.setReadTimeout(timeout);
            connection.setFollowRedirects(true);
            connection.connect();
            OutputStream outStrm = connection.getOutputStream();
            outStrm.write(bytes);
            outStrm.flush();
            outStrm.close();
            InputStream inStrm = connection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, encode));

            String temp = "";
            while ((temp = br.readLine()) != null) {
                html += (temp + '\n');
            }
            br.close();
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return html;

    }
}