6

场景: 我正在尝试通过服务中的 HttpURLConnection 发送一些 POST 数据(带有进度更新)。我从图库中抓取图像,然后将其发送到具有 2 个参数的 php 服务器;invnum 和密码。

注意: 如果我是通过 HttpClient 方法进行的,则参数和图像在服务器中发送和接收,但我无法跟踪上传进度。我看到了一些与自定义多部分实体相关的代码,我想尽可能避免引用库

我在 SO 中研究了很多相关问题,但似乎找不到解决方案。以下是我服务中的当前代码。

protected void onHandleIntent(Intent intent) {
    String invnum = intent.getStringExtra("invnum");
    String uploadURL = intent.getStringExtra("uploadURL");
    String imageURI = intent.getStringExtra("imageURI");
    uri = Uri.parse(imageURI);

    String pass = "password";

    //get the actual path of the image residing in the phone
    String[] filePathColumn = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(uri,filePathColumn, null, null, null);
    cursor.moveToFirst();
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    picturePath = cursor.getString(columnIndex);
    cursor.close();

    ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");

    //check url
    try {
        File file = new File(picturePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] bytes = new byte[(int) file.length()];
        fileInputStream.read(bytes);
        fileInputStream.close();

        String fileName = file.getName();

        URL url = new URL(uploadURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);
        connection.setChunkedStreamingMode(1024);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)");
        connection.setRequestProperty("image", fileName);
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        //send multipart form data (required) for file
        outputStream.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\"" + fileName + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
        //outputStream.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(fileName) + lineEnd);
        //outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
        //outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd);
        outputStream.writeBytes("Content-Length: " + file.length() + lineEnd);
        outputStream.writeBytes(lineEnd);

        int bufferLength = 1024;
        for (int i = 0; i < bytes.length; i += bufferLength) {
            // publishing the progress....
            Bundle resultData = new Bundle();
            resultData.putInt("progress" ,(int)((i / (float) bytes.length) * 100));
            receiver.send(UPDATE_PROGRESS, resultData);

            if (bytes.length - i >= bufferLength) {
                outputStream.write(bytes, i, bufferLength);
            } else {
                outputStream.write(bytes, i, bytes.length - i);
            }
        }

        //end output
        outputStream.writeBytes(lineEnd);

        //write more parameters other than the file
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        //outputStream.writeBytes(twoHyphens + boundary + lineEnd); //less twohyphens
        outputStream.writeBytes("Content-Disposition: form-data; name=\"invnum\"" + lineEnd);
        //outputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
        //outputStream.writeBytes("Content-Length: " + invnum.length() + lineEnd);
        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(invnum + lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);

        outputStream.writeBytes("Content-Disposition: form-data; name=\"pass\"" + lineEnd);
        //outputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
        //outputStream.writeBytes("Content-Length: " + pass.length() + lineEnd);
        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(pass + lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // publishing the progress....
        Bundle resultData = new Bundle();
        resultData.putInt("progress", 100);
        receiver.send(UPDATE_PROGRESS, resultData);

        outputStream.flush();
        outputStream.close();
        //input ignored for now

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

运行应用程序时,进度很好地反映了,但是在我的服务器上检查时,根本没有上传任何文件。事实上,服务器没有发送或接收任何数据。有谁知道可能导致此问题的原因是什么?下面是我的服务器代码。

$pass = $_POST['pass'];
$invnum = $_POST['invnum'];
$image = $_POST['image'];
if ($pass == 'password') {
    //do something
}

更新: 首先,我从 HTTPURLConnection 收到 404 错误。我的网址看起来像“ http://www.xyz.com/upload.php ”。更新到前一句,去掉“setChunkedStreamingMode”,我可以成功上传参数到服务器,但不能上传图片!快到了!

4

2 回答 2

7

终于让它工作了...

行“connection.setChunkedStreamingMode(1024);” 导致问题。删除后,参数和文件的上传成功。一个小问题仍然存在,上传进度不准确。返回的进度实际上是缓冲区被填满,即使是 3MB 的图像也几乎是瞬时的。进度达到100后,文件仍在后台上传。猜猜这将是另一个问题。

于 2013-10-10T03:40:12.840 回答
0

In android HttpClient method better than HttpUrlConnection. I only show how exceute post method with HttpClient. I used this samly structer;

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(<n>);// you have pass, invnum and image
nameValuePairs.add(new BasicNameValuePair("image", "<filName>"));
post.setEntity( new UrlEncodedFormEntity(nameValuePairs));
client.execute(post);
于 2013-10-09T04:51:48.170 回答