Upload File to Server from Java Client without any library

Here is example code which can upload files to any server without using any third party library in java

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

import com.linkwithweb.callback.ResponseHandler;

/**
* @author kumara
*
*/
public class HttpPost {
URL u;
private static CookieManager cm = new CookieManager();

/**
* @param args
*/
public static void main(String args[]) {
// post();
new HttpPost().sendFile("http://localhost:8080/Server/LoginServlet",
"serverxml/login.xml");
}

/**
*
*/
private void post() {

String s = URLEncoder.encode("A Test string to send to a servlet");

try {
HttpPost post = new HttpPost();
post.u = new URL("http://myhost/servlet");

// Open the connection and prepare to POST
URLConnection uc = u.openConnection();
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setAllowUserInteraction(false);

DataOutputStream dstream = new DataOutputStream(
uc.getOutputStream());

// The POST line
dstream.writeBytes(s);
dstream.close();

// Read Response
InputStream in = uc.getInputStream();
int x;
while ((x = in.read()) != -1) {
System.out.write(x);
}
in.close();

BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuffer buf = new StringBuffer();
String line;
while ((line = r.readLine()) != null) {
buf.append(line);
}

} catch (IOException e) {
e.printStackTrace(); // should do real exception handling
}
}

/**
* @param url
* Url to send data to
* @param file1
* path to local file to upload
* @return int if 0 then all ok else see value and look in code!
*/
public int sendFile(String surl, String file1) {

int rtn = 1;

HttpURLConnection conn = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null;

InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";
String exsistingFileName = file1;
File fFile2Snd = new File(exsistingFileName);

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "***232404jkg4220957934FW**";

int bytesRead, bytesAvailable, bufferSize;

byte[] buffer;

int maxBufferSize = 1 * 1024 * 1024;

String responseFromServer = "";

String urlString = surl;// "http://localhost:81/FileUpload/requestupload";
// urlString =
// "http://a.com/sel2in/prjs/php/p12/skewmypic/v1/getBytes.php";

try {
// ------------------ CLIENT REQUEST

FileInputStream fileInputStream = new FileInputStream(new File(
exsistingFileName));
rtn++;

// open a URL connection to the Servlet

URL url = new URL(urlString);
rtn++;

// Open a HTTP connection to the URL

conn = (HttpURLConnection) url.openConnection();

// Allow Inputs
conn.setDoInput(true);

// Allow Outputs
conn.setDoOutput(true);

// Don't use a cached copy.
conn.setUseCaches(false);

// Use a post method.
conn.setRequestMethod("POST");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);

dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"userfile\";"
+ " filename=\"" + fFile2Snd.getName() + "\"" + lineEnd);
dos.writeBytes(lineEnd);

rtn++;

// create a buffer of maximum size

bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// read file and write it into form...

bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

// send multipart form data necesssary after file data...

dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// close streams

fileInputStream.close();
dos.flush();
dos.close();

} catch (MalformedURLException ex) {
System.out.println("From ServletCom2 CLIENT REQUEST:" + ex);
}

catch (IOException ioe) {
System.out.println("From ServletCom2 CLIENT REQUEST:" + ioe);
}

// ------------------ read the SERVER RESPONSE

try {
System.out.println("Server response is: \n");
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
System.out.println(str);
System.out.println("");
}
inStream.close();
System.out.println("\nEND Server response ");

} catch (IOException ioex) {
System.out.println("From (ServerResponse): " + ioex);

}
rtn = 0;
return rtn;

}

/**
* @param fileContent
* content of file
* @param contextParams
* TODO
* @param url
* Url to send data to
* @return int if 0 then all ok else see value and look in code!
*/
public int uploadStringAsFile(String surl, String fileContent,
String requestIdentifier, ResponseHandler responseHandler,
Map contextParams) {
fileContent = fileContent.trim();
int rtn = 1;
HttpURLConnection conn = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null;

InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "***232404jkg4220957934FW**";

int bytesRead, bytesAvailable, bufferSize;

byte[] buffer;

int maxBufferSize = 1 * 1024 * 1024;

String responseFromServer = "";

String urlString = surl;// "http://localhost:81/FileUpload/requestupload";
// urlString =
// "http://a.com/sel2in/prjs/php/p12/skewmypic/v1/getBytes.php";

try {
// ------------------ CLIENT REQUEST

rtn++;

// open a URL connection to the Servlet

URL url = new URL(urlString);
rtn++;

// Open a HTTP connection to the URL

conn = (HttpURLConnection) url.openConnection();
cm.setCookies(conn);

// Allow Inputs
conn.setDoInput(true);

// Allow Outputs
conn.setDoOutput(true);

// Don't use a cached copy.
conn.setUseCaches(false);

// Use a post method.
conn.setRequestMethod("POST");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);

dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"userfile\";"
+ " filename=\"file\"" + lineEnd);
dos.writeBytes(lineEnd);

rtn++;

// create a buffer of maximum size

bytesAvailable = fileContent.getBytes("UTF-8").length;
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// read file and write it into form...

dos.write(fileContent.getBytes("UTF-8"), 0, bufferSize);

// send multipart form data necesssary after file data...

dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// close streams

dos.flush();
dos.close();

} catch (MalformedURLException ex) {
System.out.println("From ServletCom2 CLIENT REQUEST:" + ex);
}

catch (IOException ioe) {
System.out.println("From ServletCom2 CLIENT REQUEST:" + ioe);
}

// ------------------ read the SERVER RESPONSE

StringBuffer returnString = new StringBuffer();

try {
// System.out.println("Server response is: \n");
cm.storeCookies(conn);

inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
returnString.append(str + "\r\n");
}
inStream.close();
// System.out.println("\nEND Server response ");

} catch (IOException ioex) {
System.out.println("From (ServerResponse): " + ioex);

} finally {
if (responseHandler != null) {
responseHandler.hadleResponse(requestIdentifier,
returnString.toString(), contextParams);
}
}
rtn = 0;
return rtn;

}

/**
* @param urlString
*/
public void storeAndGetCookies(String urlString) {
CookieManager cm = new CookieManager();
try {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.connect();
cm.storeCookies(conn);
System.out.println(cm);
cm.setCookies(url.openConnection());
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

}

Advertisements

One thought on “Upload File to Server from Java Client without any library

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s