如何将3个图像和数据发送到服务器?

时间:2017-08-17 07:36:18

标签: android json

响应ID响应ID 525295未在此过程中提供

 RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);

//Create your body
  JSONObject jsonRequest = new JSONObject();
            try {
                jsonRequest.put("photo_one", byteArrayToHexString(imageByteArray1));
                jsonRequest.put("photo_two", byteArrayToHexString(imageByteArray2));
                jsonRequest.put("photo_three", byteArrayToHexString(imageByteArray3));
                jsonRequest.put("product_titile", mTitle.getText().toString());
                jsonRequest.put("product_description", mDiscription.getText().toString());
                jsonRequest.put("location", mAddress.getText().toString());
                jsonRequest.put("name", mPername.getText().toString());
                jsonRequest.put("mobile", mPerMobile.getText().toString());
            } catch (JSONException e) {
                Log.i("Exception", e.toString());
            }

            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonRequest, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.v("Response", response.toString());
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.v("Error", error.getMessage());
                }
            }){
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();

                    headers.put("Content-Type", "application/json; charset=utf-8");

                    return headers;
                }
            };

                //Add request to queue
                queue.add(jsonObjectRequest);

@NonNull
private static String byteArrayToHexString (byte[] a) {
    StringBuilder sb = new StringBuilder(a.length * 2);
    for (byte b : a)
        sb.append(String.format("%02x", b & 0xff));
    return sb.toString();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK && data != null) {
        filePaths = data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA);
        Spacecraft s;
        ArrayList<Spacecraft> spacecrafts = new ArrayList<>();
        //Uri filePath = data.getData();
        try {
            for (String path : filePaths) {
                s = new Spacecraft();
                s.setName(path.substring(path.lastIndexOf("/") + 1));
                Log.v("image", path);
                s.setUri(Uri.fromFile(new File(path)));
                spacecrafts.add(s);
                //bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.parse(path));
            }
            gv.setAdapter(new CustomAdapter(this, spacecrafts));
            Toast.makeText(HomeScreen.this, "Total = " + String.valueOf(spacecrafts.size()), Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        imageString = filePaths.get(0);
        Log.v("newimagestring",imageString);
        imageString2 = filePaths.get(1);
        Log.v("newimagestring",imageString2);
        imageString3 = filePaths.get(2);
        Log.v("newimagestring",imageString3);


        File image1 = new File(imageString);
        BitmapFactory.Options bmOptions1 = new BitmapFactory.Options();
        Bitmap bitmap1 = BitmapFactory.decodeFile(image1.getAbsolutePath(),bmOptions1);
        ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
        bitmap1.compress(Bitmap.CompressFormat.PNG, 100, stream1);
        imageByteArray1 = stream1.toByteArray();

        File image2 = new File(imageString2);
        BitmapFactory.Options bmOptions2 = new BitmapFactory.Options();
        Bitmap bitmap2 = BitmapFactory.decodeFile(image2.getAbsolutePath(),bmOptions2);
        ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
        bitmap2.compress(Bitmap.CompressFormat.PNG, 100, stream2);
        imageByteArray2 = stream2.toByteArray();

        File image3 = new File(imageString3);
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        Bitmap bitmap3 = BitmapFactory.decodeFile(image3.getAbsolutePath(),bmOptions);
        ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
        bitmap3.compress(Bitmap.CompressFormat.PNG, 100, stream3);
        imageByteArray3 = stream3.toByteArray();

    }
}

这是回复,

D / QcrilMsgTunnelSocket:此过程中未提供响应ID 525295。 D / QcrilMsgTunnelSocket:此过程中未提供响应ID 525295。 W / Analytics-Core-ConfigServer:HttpResponse为空。 W / Analytics-Core-ConfigServer:HttpResponse为空。 D / QcrilMsgTunnelSocket:此过程中未提供响应ID 525295。 D / com.xiaomi.common.Network:Http POST响应代码:503

4 个答案:

答案 0 :(得分:0)

这是你可以做的伎俩!

  1. 逐个选择图像时将其上传并保存响应路径。
  2. 现在将路径附加到您要发送的JSON。

  3. 最终你要在数据库中保存网址。

答案 1 :(得分:0)

首先下载httpmime-4.1-beta1.jar文件,然后将其添加为库。 see here

现在在您的活动中声明ArrayList<Filepath> filepath = new ArrayList<>();并粘贴以下代码

注意: filepath将保存您的Imagepath。

class ImageUploadTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showProgressDialog();
        }

        @Override
        protected String doInBackground(String... param) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(url);
                final String basicAuth = "Basic " + Base64.encodeToString("admin:123456".getBytes(), Base64.NO_WRAP);
                httpPost.setHeader("Authorization", basicAuth);
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                ArrayList<Filepath> filepath = mCarApplication.getArrayListForImagePath();
//                for (int i = 0; i < filepath.size(); i++) {
//                    System.out.println("!!path " + filepath.get(i).getFilepath());
//                    entity.addPart("file" + String.valueOf(i), new FileBody(new File(filepath.get(i).getFilepath())));
//                }

                entity.addPart("file1", new FileBody(new File(filepath.get(0).getFilepath())));
                if (filepath.size() >= 2) {
                    entity.addPart("file2", new FileBody(new File(filepath.get(1).getFilepath())));
                }
                if (filepath.size() >= 3) {
                    entity.addPart("file3", new FileBody(new File(filepath.get(2).getFilepath())));
                }
                if (filepath.size() >= 4) {
                    entity.addPart("file4", new FileBody(new File(filepath.get(3).getFilepath())));
                }
                if (filepath.size() >= 5) {
                    entity.addPart("file5", new FileBody(new File(filepath.get(4).getFilepath())));
                }
                if (filepath.size() >= 6) {
                    entity.addPart("file6", new FileBody(new File(filepath.get(5).getFilepath())));
                }
                entity.addPart("user_id", new StringBody(application.getUserid()));


                httpPost.setEntity(entity);

                HttpResponse response;
                response = httpClient.execute(httpPost);
                resEntity = response.getEntity();


                final String response_str = EntityUtils.toString(resEntity);
                Log.e("!!TAG12", "Response " + response_str);
                return response_str;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }



        @Override
        protected void onPostExecute(String sResponse) {
            dismissProgressDialog();
            if (sResponse != null) {
                // Your code

            }
        }
    }
new ImageUploadTask().execute(); call it when you want to upload files.

你的文件路径类应该是:

public class Filepath {
    private String filepath;
    private int position;

    public Filepath(String filepath, int position) {
        this.filepath = filepath;
        this.position = position;
    }

    public void setFilepath(String filepath) {
        this.filepath = filepath;
    }

    public String getFilepath() {
        return this.filepath;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    public int getPosition() {
        return this.position;
    }

}

答案 2 :(得分:0)

为什么不尝试将图像加密为字节数组,并使用带有JSON正文的HTTP POST方法将其作为字符串发送到服务器?

要加密您的图片使用:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imageByteArray1 = stream.toByteArray();

然后创建您的JSON字符串,例如:

{ 
  "photo_one":byteArrayToHexString(imageByteArray1), 
  "photo_two":byteArrayToHexString(imageByteArray2),
  "photo_three":byteArrayToHexString(imageByteArray3),
  "product_title":"PRODUCT_TITLE",
  "product_description":"PRODUCT_DESCRIPTION",
  "location":"LOCATION",  
  "name":"NAME",
  "mobile":"MOBILE",
  ...
}

方法byteArrayToHexString将字节数组转换为HEX字符串:

    public static String byteArrayToHexString(byte[] a) {
        StringBuilder sb = new StringBuilder(a.length * 2);
        for(byte b: a)
            sb.append(String.format("%02x", b & 0xff));
        return sb.toString();
    }

现在,HTTP将JSON正文HTTP POST到您的Web服务。有很多方法,但更简单的方法是使用Volley库,它是这样完成的:

    RequestQueue queue = Volley.newRequestQueue(this);

    //Create your body
    JSONObject jsonRequest = new JSONObject();

    try {
        jsonRequest.put("photo_one", byteArrayToHexString(imageByteArray1));
        ...
    } catch (JSONException e) {
        Log.i("Exception", e.toString())
    }

    url = "YOUR_URL";
    //Create your request
    StringRequest postRequest = new StringRequest(Request.Method.POST, url, body, new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error
             Log.d("Error.Response", response);
       }
    }
    ) {     
    @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();

            headers.put("Content-Type", "application/json; charset=utf-8");

            return headers;
        }
    };

    //Add request to queue
    queue.add(postRequest);

最后,当您取回数据时,只需将字节数组解码为Bitmap

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

编辑1:

要使用voley库,只需将此行添加到依赖项部分中的APP build.gradle

compile 'com.android.volley:volley:1.0.0'

编辑2:

要从路径转换图像文件,请使用以下命令:

File image = new File(YOUR_PATH_TO_IMAGE);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);

希望有所帮助:)

答案 3 :(得分:0)

我遇到了完全相同的问题,然后用一个库来解决这个问题。这很容易。只有两个步骤:

  • 将库添加到项目中

    compile 'net.gotev:uploadservice:3.0'
    
  • 此代码用于发送数据:

     try {
        String uploadId = UUID.randomUUID().toString();
        new MultipartUploadRequest(getApplicationContext(), uploadId, APIAddresses.save_record_url)
                .addFileToUpload(ImagePath1, "photo_one")
                .addFileToUpload(ImagePath2, "photo_two")
                .addFileToUpload(ImagePath3, "photo_three")
                .addParameter("product_title","title")
                .addParameter("product_description","description)
                .addParameter("location","location)
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .setDelegate(new UploadStatusDelegate() {
                    @Override
                    public void onProgress(UploadInfo uploadInfo) {
                        progressDialog.show();
                    }
    
                    @Override
                    public void onError(UploadInfo uploadInfo, Exception exception) {
    
                    }
    
                    @Override
                    public void onCompleted(UploadInfo uploadInfo, ServerResponse serverResponse) {
                        progressDialog.dismiss();
                        finish();
                        System.out.println(serverResponse);
    
                    }
    
                    @Override
                    public void onCancelled(UploadInfo uploadInfo) {
    
                    }
                })
                .startUpload();
    
    
    } catch (Exception exc) {
        UtilityMethods.showToast(this,exc.getMessage());
    }
    

代码非常简单且不言自明,所以我认为我不需要解释它是如何工作的。添加尽可能多的图像和参数。尝试一下,如果有效就投票。 我现在没有图书馆的链接。您可以在Google上搜索,也可以找到它。

祝你好运!