Send file from Android to Servlet via HttpConnection POST
I have this code on my android:
try {
http = (HttpConnection) Connector.open("http://35.9.22.102:8080/Services/SubmitMedia/");
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Connection", "keep-alive");
http.setRequestProperty("Content-Type", "multipart/form-data");
http.setRequestProperty("Content-Length", fil开发者_C百科e.length + "");
dos = http.openDataOutputStream();
dos.write(file);
int response = ((HttpConnection) http).getResponseCode();
if (response == HttpConnection.HTTP_OK) System.out.println("Success");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (http != null) http.close();
if (dos != null) dos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This code for the servlet side:
DataInputStream din = new DataInputStream(request.getInputStream());
byte[] data = new byte[0];
byte[] buffer = new byte[512];
int bytesRead;
while ((bytesRead = din.read(buffer)) > 0 ) {
// construct large enough array for all the data we now have
byte[] newData = new byte[data.length + bytesRead];
// copy data previously read
System.arraycopy(data, 0, newData, 0, data.length);
// append data newly read
System.arraycopy(buffer, 0, newData, data.length, bytesRead);
// discard the old array in favour of the new one
data = newData;
}
The problem is the code broke when it reaches Connector.open("http://35.9.22.102:8080/Services/SubmitMedia/")
on the Android part. The program skips whole thing and goes to finally
. I am not sure what would be the main problem in here. I need some help.
精彩评论