Uploading an image using HttpUrlConnection
I am trying to upload an image from my device file system to a server. The upload works fine when i use a WIFI connection, but fails when on GPRS. My code is as below:
String request=null;
byte[] attachmentData;
//read the image from the 开发者_运维知识库file system
attachmentData=bytesReadfromthefilesystem;
//I use Apache's Base64 encoding to convert the byte array to string
request=Base64.encode(data);
URL url = new URL(
"http://mydomain.com:9090//abc/http?ID=12345");
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setRequestProperty("Content-Type",
"text/plain");
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setChunkedStreamingMode(0);
httpURLConnection.connect();
OutputStream outStream outStream =httpURLConnection.getOutputStream();
if (outStream != null) {
if (request.getData().length() > 0) {
outStream.write(request.getBytes());
}
outStream.flush();
outStream.close();
outStream = null;
}
The image size is close to 1MB. I am trying on Samsung Galaxy Pop (Android 2.2.1). I do not get any errors too. Am i missing out on something here? Could someone kindly help me with this? Thanks in advance.
did you set the permission on your AndroidManifest file?
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
Try to setConnectionTimeout()
to 300000 (5 minutes) or something like that.
精彩评论