Switch to full style
Project under GPL source codes are posted here
Post a reply

Multipart HTTP forms submitter - With Progress Information

Sat Nov 08, 2008 1:04 am

 Project Name:   Multipart HTTP forms submitter - With Progress Information
 Programmer:   Tomer Petel
 Type:   Web
 Technology:  Java
 IDE:   NONE
 Description:   In one of my projects, I had to be able to submit a data to the Web server using HTTP. The issue was that this data was multipart that is, a combination of binary data and text data. So a simple GET or POST call would not have been sufficient. To my rescue, came Vlad Patryshevs class: ClientHTTPRequest. This highly versatile class allows you to easily submit multipart data via HTTP. However it was missing one thing: progress information. That is, when sending a large file via HTTP, the users would need to know how much of the file was already sent and how much more still remains to be sent. Therefore, I extended Vlads class to provide upload progress information.
Code sample :
java code
import java.net.*;
import java.io.*;
import java.util.*;
/**
* <p>Title: Client HTTP Request class</p>
* <p>Description: this class helps to send POST HTTP requests with various form data and also allows for progress
* to be shown
* including files. Cookies can be added to be included in the request.</p>
*
* @author Tomer Petel
* @version 1.0
* This is an Enhancement of ClientHTTPRequest, written by Vlad Patryshev
*/
public class ClientHttpRequest2 {

URL _url=null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Map cookies = new HashMap();
SubmitProgress _sp=null;
StringBuffer cookieList = new StringBuffer();

protected URLConnection getConnection(int contentLength) throws Exception {
HttpURLConnection connection = (HttpURLConnection)_url.openConnection();
connection.setFixedLengthStreamingMode(contentLength);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
if (_sp!=null) {
_sp.setBytesToTransfer(contentLength);
}
if (cookieList.length() > 0) {
connection.setRequestProperty("Cookie", cookieList.toString());
}
return connection;
}

protected void write(char c) throws Exception {
baos.write(c);
}

protected void write(String s) throws Exception {
baos.write(s.getBytes());
}

protected void newline() throws Exception {
write("\r\n");
}

protected void writeln(String s) throws Exception {
write(s);
newline();
}

private static Random random = new Random();

protected static String randomString() {
return Long.toString(random.nextLong(), 36);
}

String boundary = "---------------------------" + randomString() + randomString() + randomString();

private void boundary() throws Exception {
write("--");
write(boundary);
}

/**
* Creates a new multipart POST HTTP request for a specified URL
*
* @param url the URL to send request to
* @throws Exception
*/
public ClientHttpRequest2(URL url) throws Exception {
_url=url;
}

/**
* Creates a new multipart POST HTTP request for a specified URL string
*
* @param urlString the string representation of the URL to send request to
* @throws Exception
*/
public ClientHttpRequest2(String urlString) throws Exception {
this(new URL(urlString));
}


private void postCookies() {
cookieList.delete(0, cookieList.length());
for (Iterator i = cookies.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry)(i.next());
cookieList.append(entry.getKey().toString() + "=" + entry.getValue());

if (i.hasNext()) {
cookieList.append("; ");
}
}
}

//if you want to be notified for submission progress
public void setSubmitProgress(SubmitProgress sp) {
_sp=sp;
}

/**
* adds a cookie to the requst
* @param name cookie name
* @param value cookie value
* @throws Exception
*/
public void setCookie(String name, String value) throws Exception {
cookies.put(name, value);
}

/**
* adds cookies to the request
* @param cookies the cookie "name-to-value" map
* @throws Exception
*/
public void setCookies(Map cookies) throws Exception {
if (cookies == null) return;
this.cookies.putAll(cookies);
}

/**
* adds cookies to the request
* @param cookies array of cookie names and values
(cookies[2*i] is a name, cookies[2*i + 1] is a value)
* @throws Exception
*/
public void setCookies(String[] cookies) throws Exception {
if (cookies == null) return;
for (int i = 0; i < cookies.length - 1; i+=2) {
setCookie(cookies[i], cookies[i+1]);
}
}

private void writeName(String name) throws Exception {
newline();
write("Content-Disposition: form-data; name=\"");
write(name);
write('"');
}

/**
* adds a string parameter to the request
* @param name parameter name
* @param value parameter value
* @throws Exception
*/
public void setParameter(String name, String value) throws Exception {
boundary();
writeName(name);
newline(); newline();
writeln(value);
}

private void pipe(InputStream in, OutputStream out, boolean measureProgress) throws Exception {
byte[] buf = new byte[50000];
int nread;
int navailable;
int total = 0;
synchronized (in) {
while((nread = in.read(buf, 0, buf.length)) >= 0) {
out.write(buf, 0, nread);
total += nread;
if ((_sp!=null) && (measureProgress)) {
out.flush();
_sp.bytesTransferred(total);
}
}
}
out.flush();
buf = null;
}

/**
* adds a file parameter to the request
* @param name parameter name
* @param filename the name of the file
* @param is input stream to read the contents of the file from
* @throws Exception
*/
public void setParameter(String name, String filename, InputStream is) throws Exception {
boundary();
writeName(name);
write("; filename=\"");
write(filename);
write('"');
newline();
write("Content-Type: ");
String type = "application/octet-stream";
writeln(type);
newline();
pipe(is, baos, false);
newline();
}

/**
* adds a file parameter to the request
* @param name parameter name
* @param file the file to upload
* @throws Exception
*/
public void setParameter(String name, File file) throws Exception {
setParameter(name, file.getPath(), new FileInputStream(file));
}

/**
* adds a parameter to the request; if the parameter is a File, the file is uploaded,
otherwise the string value of the parameter is passed in the request
* @param name parameter name
* @param object parameter value, a File or anything else that can be stringified
* @throws Exception
*/
public void setParameter(String name, Object object) throws Exception {
if (object instanceof File) {
setParameter(name, (File) object);
} else {
setParameter(name, object.toString());
}
}

/**
* adds parameters to the request
* @param parameters "name-to-value" map of parameters;
if a value is a file, the file is uploaded, otherwise it is stringified and sent in the request
* @throws Exception
*/
public void setParameters(Map parameters) throws Exception {
if (parameters == null) return;
for (Iterator i = parameters.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry)i.next();
setParameter(entry.getKey().toString(), entry.getValue());
}
}

/**
* adds parameters to the request
* @param parameters array of parameter names and values
(parameters[2*i] is a name, parameters[2*i + 1] is a value);
if a value is a file, the file is uploaded, otherwise it is stringified and sent in the request
* @throws Exception
*/
public void setParameters(Object[] parameters) throws Exception {
if (parameters == null) return;
for (int i = 0; i < parameters.length - 1; i+=2) {
setParameter(parameters[i].toString(), parameters[i+1]);
}
}

/**
* posts the requests to the server, with all the cookies and parameters that were added
* @return input stream with the server response
* @throws Exception
*/
public InputStream post() throws Exception {
boundary();
writeln("--");
baos.close();
int length=baos.size();
URLConnection connection=getConnection(length);
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
OutputStream os=connection.getOutputStream();
pipe(bais,os , true);

//should go straight to the net, thanks to setFixedLengthStreamingMode()

// if (_sp!=null) {
// _sp.statusMessage("Audio Transferred. Awaiting server response...");
// }
os.close();
return connection.getInputStream();
}

/**
* posts the requests to the server, with all the cookies and
parameters that were added before (if any), and with parameters that are passed in the argument
* @param parameters request parameters
* @return input stream with the server response
* @throws Exception
* @see setParameters
*/
public InputStream post(Map parameters) throws Exception {
setParameters(parameters);
return post();
}

/**
* posts the requests to the server, with all the cookies
and parameters that were added before (if any), and with parameters that are passed in the argument
* @param parameters request parameters
* @return input stream with the server response
* @throws Exception
* @see setParameters
*/
public InputStream post(Object[] parameters) throws Exception {
setParameters(parameters);
return post();
}

/**
* posts the requests to the server, with all the cookies
and parameters that were added before (if any), and with cookies and parameters that are passed in the arguments
* @param cookies request cookies
* @param parameters request parameters
* @return input stream with the server response
* @throws Exception
* @see setParameters
* @see setCookies
*/
public InputStream post(Map cookies, Map parameters) throws Exception {
setCookies(cookies);
setParameters(parameters);
return post();
}

/**
* posts the requests to the server, with all the cookies and
parameters that were added before (if any), and with cookies and parameters that are passed in the arguments
* @param cookies request cookies
* @param parameters request parameters
* @return input stream with the server response
* @throws Exception
* @see setParameters
* @see setCookies
*/
public InputStream post(String[] cookies, Object[] parameters) throws Exception {
setCookies(cookies);
setParameters(parameters);
return post();
}

/**
* post the POST request to the server, with the specified parameter
* @param name parameter name
* @param value parameter value
* @return input stream with the server response
* @throws Exception
* @see setParameter
*/
public InputStream post(String name, Object value) throws Exception {
setParameter(name, value);
return post();
}

/**
* post the POST request to the server, with the specified parameters
* @param name1 first parameter name
* @param value1 first parameter value
* @param name2 second parameter name
* @param value2 second parameter value
* @return input stream with the server response
* @throws Exception
* @see setParameter
*/
public InputStream post(String name1, Object value1, String name2, Object value2) throws Exception {
setParameter(name1, value1);
return post(name2, value2);
}

/**
* post the POST request to the server, with the specified parameters
* @param name1 first parameter name
* @param value1 first parameter value
* @param name2 second parameter name
* @param value2 second parameter value
* @param name3 third parameter name
* @param value3 third parameter value
* @return input stream with the server response
* @throws Exception
* @see setParameter
*/
public InputStream post
(String name1, Object value1, String name2, Object value2, String name3, Object value3)
throws Exception {
setParameter(name1, value1);
return post(name2, value2, name3, value3);
}

/**
* post the POST request to the server, with the specified parameters
* @param name1 first parameter name
* @param value1 first parameter value
* @param name2 second parameter name
* @param value2 second parameter value
* @param name3 third parameter name
* @param value3 third parameter value
* @param name4 fourth parameter name
* @param value4 fourth parameter value
* @return input stream with the server response
* @throws Exception
* @see setParameter
*/
public InputStream post(String name1, Object value1,
String name2, Object value2, String name3, Object value3, String name4, Object value4)
throws Exception {
setParameter(name1, value1);
return post(name2, value2, name3, value3, name4, value4);
}

/**
* posts a new request to specified URL, with parameters that are passed in the argument
* @param parameters request parameters
* @return input stream with the server response
* @throws Exception
* @see setParameters
*/
public static InputStream post(URL url, Map parameters) throws Exception {
return new ClientHttpRequest2(url).post(parameters);
}

/**
* posts a new request to specified URL, with parameters that are passed in the argument
* @param parameters request parameters
* @return input stream with the server response
* @throws Exception
* @see setParameters
*/
public static InputStream post(URL url, Object[] parameters) throws Exception {
return new ClientHttpRequest2(url).post(parameters);
}

/**
* posts a new request to specified URL,
with cookies and parameters that are passed in the argument
* @param cookies request cookies
* @param parameters request parameters
* @return input stream with the server response
* @throws Exception
* @see setCookies
* @see setParameters
*/
public static InputStream post(URL url, Map cookies, Map parameters) throws Exception {
return new ClientHttpRequest2(url).post(cookies, parameters);
}

/**
* posts a new request to specified URL, with cookies
and parameters that are passed in the argument
* @param cookies request cookies
* @param parameters request parameters
* @return input stream with the server response
* @throws Exception
* @see setCookies
* @see setParameters
*/
public static InputStream post(URL url, String[] cookies, Object[] parameters) throws Exception {
return new ClientHttpRequest2(url).post(cookies, parameters);
}

/**
* post the POST request specified URL, with the specified parameter
* @param name parameter name
* @param value parameter value
* @return input stream with the server response
* @throws Exception
* @see setParameter
*/
public static InputStream post(URL url, String name1, Object value1) throws Exception {
return new ClientHttpRequest2(url).post(name1, value1);
}

/**
* post the POST request to specified URL, with the specified parameters
* @param name1 first parameter name
* @param value1 first parameter value
* @param name2 second parameter name
* @param value2 second parameter value
* @return input stream with the server response
* @throws Exception
* @see setParameter
*/
public static InputStream post
(URL url, String name1, Object value1, String name2, Object value2) throws Exception {
return new ClientHttpRequest2(url).post(name1, value1, name2, value2);
}

/**
* post the POST request to specified URL, with the specified parameters
* @param name1 first parameter name
* @param value1 first parameter value
* @param name2 second parameter name
* @param value2 second parameter value
* @param name3 third parameter name
* @param value3 third parameter value
* @return input stream with the server response
* @throws Exception
* @see setParameter
*/
public static InputStream post
(URL url, String name1, Object value1, String name2, Object value2, String name3, Object value3)
throws Exception {
return new ClientHttpRequest2(url).post(name1, value1, name2, value2, name3, value3);
}

/**
* post the POST request to specified URL, with the specified parameters
* @param name1 first parameter name
* @param value1 first parameter value
* @param name2 second parameter name
* @param value2 second parameter value
* @param name3 third parameter name
* @param value3 third parameter value
* @param name4 fourth parameter name
* @param value4 fourth parameter value
* @return input stream with the server response
* @throws Exception
* @see setParameter
*/
public static InputStream post(URL url, String name1, Object value1, String name2, Object value2, String name3, Object value3, String name4, Object value4)

throws Exception {
return new ClientHttpRequest2(url).post(name1, value1, name2, value2, name3, value3, name4, value4);
}
}

ClientHTTPRequest2.gif
ClientHTTPRequest2.gif (7.38 KiB) Viewed 4751 times



Attachments
ClientHTTPRequest2_src.zip
(4.97 KiB) Downloaded 878 times

Re: Multipart HTTP forms submitter - With Progress Information

Sun Jan 20, 2013 10:09 pm

updated.

Post a reply
  Related Posts  to : Multipart HTTP forms submitter - With Progress Information
 status Progress bar     -  
 Progress dialog     -  
 Show Progress Bar using JQuery     -  
 Using forms with ASP     -  
 php forms     -  
 Secure forms without using captcha     -  
 HTTP Server in Java     -  
 Send parameters using HTTP GET     -  
 http proxy code     -  
 Using java in http connection     -  

Topic Tags

Java Projects