通过HttpURLConnection将参数和图像上传到PHP服务器(Android)

时间:2013-10-09 03:57:24

标签: php android service httpclient httpurlconnection

情境: 我正在尝试通过服务中的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”,我能够成功将参数上传到服务器而不是图像!我很亲密!

2 个答案:

答案 0 :(得分:7)

最后让它发挥作用......

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

答案 1 :(得分:0)

在android HttpClient方法中优于HttpUrlConnection。我只用HttpClient展示了post方法的优异性。我使用了这个狡猾的结构;

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