多部分请求不在设备中工作

时间:2016-04-05 12:52:46

标签: android post multipartform-data

我正在尝试使用多部分请求,它在模拟器中工作正常但在设备中没有。 清单中有互联网许可 我在调试过程中发现的唯一区别是文件路径 设备中的/storage/sdcard0/MyApp/1459860187736.png

模拟器中的

/storage/emulated/0/MyApp/1459860187736.png

请求仅在设备上抛出无效参数错误。

        DefaultHttpClient client = new DefaultHttpClient();
        HttpParams http_params = new BasicHttpParams();

        http_params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
                HttpVersion.HTTP_1_1);
        HttpConnectionParams.setConnectionTimeout(http_params,
                60000);
        HttpConnectionParams.setSoTimeout(http_params, 60000);
        HttpPost post = new HttpPost(serverUrl);
        HttpResponse response = null;
        BasicResponseHandler myHandler = new BasicResponseHandler();
        String result = null;

            if (nameValuePairs != null) {
                MultipartEntity entity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                for (int index = 0; index < nameValuePairs.size(); index++) {

                    if (nameValuePairs.get(index).getName().equals("image")) {

                        if(nameValuePairs.get(index).getValue() != null && nameValuePairs.get(index).getValue().isEmpty()){
                            Drawable drawable = getResources().getDrawable(R.drawable.anonymoususer);
                                Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();

                                // Add binary body

                                    File file = bitmapToFile(bitmap);
                                    FileBody body = new FileBody(file);
                                    entity.addPart("image", body);

                        }else {
                            entity.addPart(nameValuePairs.get(index).getName(),
                                    new FileBody(new File(nameValuePairs.get(index)
                                                                        .getValue())));
                        }
                    } else {
                        entity.addPart(nameValuePairs.get(index).getName(),
                                new StringBody(nameValuePairs.get(index)
                                                             .getValue()));
                    }
                }


                post.setEntity(entity);
            }
            response = client.execute(post);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        res = in.readLine();//.toString();

0 个答案:

没有答案