使用HttpUrlConnection上传图像

时间:2011-07-27 10:02:24

标签: android

我正在尝试将图像从我的设备文件系统上传到服务器。当我使用 WIFI 连接时上传工作正常,但在 GPRS 时失败。我的代码如下:

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;      
      }

图像尺寸接近1MB。我正在尝试三星Galaxy Pop(Android 2.2.1)。我也没有得到任何错误。我错过了这里的东西吗?有人可以帮我这个吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

您是否在AndroidManifest文件上设置了权限?

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

答案 1 :(得分:-1)

尝试setConnectionTimeout()到300000(5分钟)或类似的东西。