tags:

views:

256

answers:

3

How can I post a file to a php using java (as a html form would do) ?

+4  A: 

If you simply need to generate an HTTP Post, check out HttpClient, and in particular the PostMethod. Since you're talking HTTP the implementing technology on the server (in your case, PHP) is immaterial.

There's an example here.

Brian Agnew
+1  A: 

The httpclient library contains all the tools you need to talk to a web server.

Aaron Digulla
+2  A: 

It is in fact possible to do a POST using only the classes that are in the JDK, but as others have pointed out it will probably be easier to use a library like HttpClient.

In addition to HttpClient you may also want to look at the client-side java libraries supplied by RESTful frameworks such as Restlet and Jersey. While primarily designed for interacting with web services they offer a very high-level abstraction for GETing and POSTing to just about anything.

Code NOT tested or even compiled (probably doesn't compile), but this is kinda sorta would you'd do if you wanted to roll your own:

URL url = new URL("http://hostname/foo.php");

URLConnection connection = url.openConnection();

connection.setDoInput(true);
connection.setDoOutput(true);

// ignoring possible encoding issues
byte[] body = "param=value&param2=value2".getBytes();

connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded" );
connection.setRequestProperty("Content-length", String.valueOf(body.length) );

// ignoring possible IOExceptions
OutputStream out = connection.getOutputStream();
out.write(body);
out.flush();

// use this to read back from server
InputStream in = connection.getInputStream();

As you can see, it's pretty low-level stuff. Which is why you want to use a library.

Licky Lindsay
I managed to POST a string, but what if I want to POST a file?
János Harsányi
If you wanted to do it manually you'd have to implement RFC 1867 I believe. (http://tools.ietf.org/html/rfc1867) But seriously, don't.
Licky Lindsay
I just want to post a file. (not text, for example a binary file)
János Harsányi