How do I upload a file using a Java client (not a browser) and HTTP POST? Many of the examples show how a HTML page can be constructed to select the file and do the POST, but I need to do it from a java client.

Richard Raszka

[Note: the following example works, but it does not encode the POSTed file in the multipart/* format expected by servlets as described in How do I upload a file to my servlet?. Perhaps another Guru could submit some feedback ...? -Alex]

Use the URLConnection class to upload a file to a web site and a servlet that understands how to read that file.

At the client level

import java.net.*;
import java.io.*;

public class HTTP_post
{
    static URL u;
    public static void main(String args[])
    {
	String s=URLEncoder.encode("A Test string to send to a servlet");

	try
	{
	    HTTP_post post = new HTTP_post();
	    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
	}
    }
}

At Servlet end

Perform a getInputStream to read the input and send the data to a file.

Example:

	    InputStream in = request.getInputStream();
	    BufferedReader r = new BufferedReader(new InputStreamReader(in));
	    StringBuffer buf = new StringBuffer();
	    String line;
	    while ((line = r.readLine())!=null) {
		buf.append(line);
	    }
	    String s = buf.toString();
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact