Blog : Send image file using java HTTP POST connections
Send image file using java HTTP POST connections
I'm trying to send an image to a website using Java HTTP POST requests. I'm using the base code used here Upload files with java: This is my modification: String urlToConnect = "http://localhost:9000/upload"; File fileToUpload = new File("C:\\Users\\joao\\Pictures\\bla.jpg"); String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
// Connection is lazily executed whenever you request any status. int responseCode = ((HttpURLConnection) connection).getResponseCode(); System.out.println(responseCode); // Should be 200 I get a 200 response code in the end, but the image is buggy, as in, random colors, which make me think it's an error in character encoding. I tried using UTF-8 as in the original example, but that just creates a corrupt image. I am also 100% sure it's not a serverside problem, because I can use rest clients such as Advanced Rest Client/Postman and they can send an image with no problems. Can you help me pinpoint what's wrong? Thank you. import java.io.File; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.util.EntityUtils;
public class PostFile { public static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:9000/upload"); File file = new File("C:\\Users\\joao\\Pictures\\bla.jpg"");
MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file, "image/jpeg"); mpEntity.addPart("userfile", cbFile);
System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println(EntityUtils.toString(resEntity)); } if (resEntity != null) { resEntity.consumeContent(); }
httpclient.getConnectionManager().shutdown(); } } Use HttpClient to work out this code. Its always better to use stable libraries other than handling from scratch, unless there is something to be handled in custom way. Reader/Writer classes are designed to handle text data, while images are binary. You need to interpret your files as binary: FileChannel in = new FileInputStream(fileToUpload).getChannel(); WritableByteChannel out = Channels.newChannel(connection.getOutputStream());
in.transferTo(0, fileToUpload.size(), out) Of course, you still need to close all opened resources Try that: private DefaultHttpClient mHttpClient; Context context; public String error = "";
//Contrutor para que metodos possam ser usados fora de uma activity public HTTPconector(Context context) { this.context = context; }
public HTTPconector() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); mHttpClient = new DefaultHttpClient(params); }
public void FileClientPost(String txtUrl, File file){ try { error = ""; HttpPost httppost = new HttpPost(txtUrl); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("Image", new FileBody(file)); httppost.setEntity(multipartEntity); mHttpClient.execute(httppost, new PhotoUploadResponseHandler()); } catch (Exception e) { Log.e(HTTPconector.class.getName(), e.getLocalizedMessage(), e); e.getStackTrace(); error = e.getMessage(); } }
//Verifica se a rede esta disponÃÂvel public boolean isNetworkAvailable() { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); // if no network is available networkInfo will be null // otherwise check if we are connected if (networkInfo != null && networkInfo.isConnected()) { return true; } return false; }
public String Get(String txtUrl){ try { URL url = new URL(txtUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setReadTimeout(10000); con.setConnectTimeout(15000); con.setRequestMethod("GET"); con.setDoInput(true); con.connect();