Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.DataOutputStream;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class Main {
    public static void post(String actionUrl, String file) {
        try {
            URL url = new URL(actionUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setRequestMethod("POST");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****");
            DataOutputStream ds = new DataOutputStream(con.getOutputStream());
            FileInputStream fStream = new FileInputStream(file);
            int bufferSize = 1024; // 1MB
            byte[] buffer = new byte[bufferSize];
            int bufferLength = 0;
            int length;
            while ((length = fStream.read(buffer)) != -1) {
                bufferLength = bufferLength + 1;
                ds.write(buffer, 0, length);
            }
            fStream.close();
            ds.flush();
            InputStream is = con.getInputStream();
            int ch;
            StringBuilder b = new StringBuilder();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            new String(b.toString().getBytes("ISO-8859-1"), "utf-8");
            ds.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}