Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;

import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import android.util.Base64;
import android.util.Log;

public class Main {
    /**
     * Tag used on log messages.
     */
    static final String TAG = "ODMCommonUtilities";
    static String gVALID_SSL = "";
    static String gDEBUG = "";

    @SuppressWarnings("resource")
    public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) {
        Logd(TAG, "Starting post...");
        String html = "";
        Boolean cont = true;
        URL url = null;
        try {
            url = new URL(targetUrl);
        } catch (MalformedURLException e) {
            Log.e(TAG, "Invalid url: " + targetUrl);
            cont = false;
            throw new IllegalArgumentException("Invalid url: " + targetUrl);
        }
        if (cont) {
            if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) {
                HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
                HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
            } else {
                // Create a trust manager that does not validate certificate chains
                TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                        // TODO Auto-generated method stub
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                        // TODO Auto-generated method stub
                    }
                } };
                // Install the all-trusting trust manager
                SSLContext sc;
                try {
                    sc = SSLContext.getInstance("SSL");
                    sc.init(null, trustAllCerts, new java.security.SecureRandom());
                    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                    // Create all-trusting host name verifier
                    HostnameVerifier allHostsValid = new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    };
                    // Install the all-trusting host verifier
                    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
                } catch (NoSuchAlgorithmException e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                } catch (KeyManagementException e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                }
            }
            Logd(TAG, "Filename: " + file);
            Logd(TAG, "URL: " + targetUrl);
            HttpURLConnection connection = null;
            DataOutputStream outputStream = null;
            String pathToOurFile = file;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024;
            try {
                connection = (HttpURLConnection) url.openConnection();
                // Allow Inputs & Outputs
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);
                //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header)
                //connection.setChunkedStreamingMode(1024);
                // Enable POST method
                connection.setRequestMethod("POST");
                setBasicAuthentication(connection, url);
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                outputStream = new DataOutputStream(connection.getOutputStream());
                //outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
                while (iterator.hasNext()) {
                    Entry<String, String> param = iterator.next();
                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\""
                            + lineEnd + lineEnd);
                    outputStream.write(param.getValue().getBytes("UTF-8"));
                    outputStream.writeBytes(lineEnd);
                }
                String connstr = null;
                if (!file.equals("")) {
                    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\""
                            + lineEnd;
                    outputStream.writeBytes(connstr);
                    outputStream.writeBytes(lineEnd);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];
                    // Read file
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    Logd(TAG, "File length: " + bytesAvailable);
                    try {
                        while (bytesRead > 0) {
                            try {
                                outputStream.write(buffer, 0, bufferSize);
                            } catch (OutOfMemoryError e) {
                                e.printStackTrace();
                                html = "Error: outofmemoryerror";
                                return html;
                            }
                            bytesAvailable = fileInputStream.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                        }
                    } catch (Exception e) {
                        Logd(TAG, "Error: " + e.getLocalizedMessage());
                        html = "Error: Unknown error";
                        return html;
                    }
                    outputStream.writeBytes(lineEnd);
                    fileInputStream.close();
                } else if (data != null) {
                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd;
                    outputStream.writeBytes(connstr);
                    outputStream.writeBytes(lineEnd);
                    bytesAvailable = data.length;
                    Logd(TAG, "File length: " + bytesAvailable);
                    try {
                        outputStream.write(data, 0, data.length);
                    } catch (OutOfMemoryError e) {
                        e.printStackTrace();
                        html = "Error: outofmemoryerror";
                        return html;
                    } catch (Exception e) {
                        Logd(TAG, "Error: " + e.getLocalizedMessage());
                        html = "Error: Unknown error";
                        return html;
                    }
                    outputStream.writeBytes(lineEnd);
                }
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                // Responses from the server (code and message)
                int serverResponseCode = connection.getResponseCode();
                String serverResponseMessage = connection.getResponseMessage();
                Logd(TAG, "Server Response Code " + serverResponseCode);
                Logd(TAG, "Server Response Message: " + serverResponseMessage);
                if (serverResponseCode == 200) {
                    InputStreamReader in = new InputStreamReader(connection.getInputStream());
                    BufferedReader br = new BufferedReader(in);
                    String decodedString;
                    while ((decodedString = br.readLine()) != null) {
                        html += decodedString;
                    }
                    in.close();
                }
                outputStream.flush();
                outputStream.close();
                outputStream = null;
            } catch (Exception ex) {
                // Exception handling
                html = "Error: Unknown error";
                Logd(TAG, "Send file Exception: " + ex.getMessage());
            }
        }
        if (html.startsWith("success:"))
            Logd(TAG, "Server returned: success:HIDDEN");
        else
            Logd(TAG, "Server returned: " + html);
        return html;
    }

    public static String post(String targetUrl, Map<String, String> params, String file) {
        return post(targetUrl, params, file, null);
    }

    public static String post(String targetUrl, Map<String, String> params, byte[] data) {
        return post(targetUrl, params, "", data);
    }

    public static String post(String targetUrl, Map<String, String> params) {
        return post(targetUrl, params, "", null);
    }

    static void Logd(String inTAG, String message) {
        if (gDEBUG.equals("true"))
            Log.d(inTAG, message);
    }

    static void setBasicAuthentication(HttpURLConnection conn, URL url) {
        String userInfo = url.getUserInfo();
        if (userInfo != null && userInfo.length() > 0) {
            String authString = Base64.encodeToString(userInfo.getBytes(), Base64.DEFAULT);
            conn.setRequestProperty("Authorization", "Basic " + authString);
        }
    }
}