Upload Files from Java Client to a Http Server

Upload files from Java client to a HTTP server

You'd normally use java.net.URLConnection to fire HTTP requests. You'd also normally use multipart/form-data encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data request body. The specification is in more detail described in RFC2388.

Here's a kickoff example:

String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.

URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// Send normal param.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();

// Send text file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
writer.append(CRLF).flush();
Files.copy(textFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

// Send binary file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
}

// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200

This code is less verbose when you use a 3rd party library like Apache Commons HttpComponents Client.

The Apache Commons FileUpload as some incorrectly suggest here is only of interest in the server side. You can't use and don't need it at the client side.

See also

  • Using java.net.URLConnection to fire and handle HTTP requests

java : upload files to HTTP server using POST, server code issue?

i hope this code can help u

try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(Image_url);
MultipartEntity mpEntity = new MultipartEntity();
File file = new File(selectedImagePath);
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("photo", cbFile);
mpEntity.addPart("user_id", new StringBody(SmallyTaxiTabbar.unique_ID));
mpEntity.addPart("password", new StringBody(SmallyTaxiTabbar.password));
post.setEntity(mpEntity);
HttpResponse response1 = client.execute(post);
HttpEntity resEntity = response1.getEntity();
String Response=EntityUtils.toString(resEntity);
Log.d("PICTUREServer Response", Response);
JSONArray jsonarray = new JSONArray("["+Response+"]");
JSONObject jsonobject = jsonarray.getJSONObject(0);
alert=(jsonobject.getString("alert"));
client.getConnectionManager().shutdown();
}
catch (Exception e) {
Log.e("TAGPost", e.toString());
}

where SmallyTaxiTabbar.unique_ID, password is parameter value

*i Hope this code can help u ! *

how to let Java HttpServer handle Post Request for File Upload

It hangs because client (Chrome, in my case) does not provide Content-Length.
RFC 1867 is pretty vague about it. It kind of suggests it but does not force it and does not have an example. Apparently clients would not always send it. The code should safeguard against missing length. Instead it goes through the loop until it reaches the end of file. Then it hangs.

Using debugger is very helpful at times.

Java Upload File via HTTP POST request

Thank you Andreas for hinting towards the content type,

I have changed this and changed from a MultiPart Entity to a FileEntity and now works fine.

import java.io.File;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.mime.HttpMultipartMode;

public class PostFile {
public static void main(String[] args) throws Exception {

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://XXXXX.XXX.XXXXXX.XXX/XX/XXXXXXX/XX/XXXXXXX/XXXXXXX");

RequestConfig requestConfig = RequestConfig.copy(RequestConfig.DEFAULT)
.setProxy(new HttpHost("XXX.XXX.XXX.XXX", 8080))
.build();
httppost.setConfig(requestConfig);

httppost.addHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");

File file = new File("batch2.txt");

FileEntity entity = new FileEntity(file);

httppost.setEntity(entity);

System.out.println("executing request " + httppost.getRequestLine() + httppost.getConfig());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

System.out.println(response.getStatusLine());
if (resEntity != null) {;
System.out.println(EntityUtils.toString(resEntity));
}

httpclient.close();
}
}


Related Topics



Leave a reply



Submit