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.IOException;
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 executePost(String targetURL, String urlParameters) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(targetURL).openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            //connection.setRequestProperty("Accept-Charset", charset);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(urlParameters.getBytes());
            } finally {
                if (output != null)
                    try {
                        output.flush();
                        output.close();
                    } catch (IOException logOrIgnore) {
                    }
            }
            InputStream response = connection.getInputStream();
            String contentType = connection.getHeaderField("Content-Type");
            String responseStr = "";
            if (true) {
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(response));
                    for (String line; (line = reader.readLine()) != null;) {
                        //System.out.println(line);
                        responseStr = responseStr + line;
                        Thread.sleep(2);
                    }
                } finally {
                    if (reader != null)
                        try {
                            reader.close();
                        } catch (IOException logOrIgnore) {
                        }
                }
            } else {
                // It's likely binary content, use InputStream/OutputStream.
                System.out.println("Binary content");
            }
            return responseStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}