使用Volley执行Post请求(Json)

时间:2018-04-29 03:04:50

标签: android android-volley

我正在尝试使用包含json主体的Volley发送POST请求我注意到这个库在S.O上有其他相关问题但是没有适当地解决我的特定用例。我和我的团队尝试了不同的变通方法,但没有成功。

我尝试了所提供代码的不同变体,并且在发送正文中包含的内容的上下文中无法获得任何工作。我试图做的是(1)帖子中的帖子(2)在该帖子中包含一个base64。我应该提一下端点,在这种情况下,正在工作并已经通过网络拦截器进行确认以及查看后端,这确实在身体中没有发送任何数据。

public class MainActivity extends AppCompatActivity {
    private TextView mTextMessage;
    private Uri capturedImageUri = null;
    static final int REQUEST_IMAGE_CAPTURE = 1;
    private ImageView imageView;
    final Context context = this;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    return true;
                case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
                    return true;
                case R.id.navigation_notifications:
                    mTextMessage.setText(R.string.title_notifications);
                    return true;
            }
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        Button btnCamera = (Button) findViewById(R.id.btnCamera);
        imageView = (ImageView) findViewById(R.id.imageView);
        btnCamera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap photo = (Bitmap) extras.get("data");
            imageView.setImageBitmap(photo);
            String convertedIMG = convertImage(photo);
            sendToRemote(convertedIMG);
        } else {
            Toast.makeText(MainActivity.this, "Could Not Capture Image, Please Try Again.", Toast.LENGTH_LONG).show();
        }
    }

    private String sendToRemote(String sendImage) {
        String url = "localhost:3000/medicalImage";
        try {

            RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
            StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.d("Response: >", response); /// put this on the UI wil contain the percentage of accuracy if positive

                        }
                    },

                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            //  imageView.setVisibility(View.GONE);
                            Log.d("network", "=========>", error);
                            error.printStackTrace();
                            Toast.makeText(MainActivity.this, "Error Submitting Image", Toast.LENGTH_LONG).show();
                        }
                    });
            // Add the request to the RequestQueue.
            queue.add(stringRequest);
        } catch (Exception error) {
            error.printStackTrace();
        }
        return "";
    }

    private String convertImage(Bitmap photo) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.JPEG, 100, out);
        byte[] b = out.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }
}

我们使用的代码------------------------------------------- ------------

 private void sendToRemote(final String sendImage) {
     String url = "url";
     try {

         JSONObject jsonBody = new JSONObject();
         jsonBody.put("Image", sendImage);
         requestBody = jsonBody.toString();
         StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                 new Response.Listener<String>() {

                     @Override
                     public void onResponse(String response) {
                         // Log.d("Response: >", response);
                         Toast.makeText(MainActivity.this, "Prediction "
                                 + response, Toast.LENGTH_LONG).show(); // returns percent of assumption
                     }
                 },
                 new Response.ErrorListener() {
                     @Override
                     public void onErrorResponse(VolleyError error) {
                         //Log.d("network", "=========>", error);
                         error.printStackTrace();
                         Toast.makeText(MainActivity.this, "Error Submitting Image", Toast.LENGTH_LONG).show();
                     }

                 }) {

             @Override
             public String getBodyContentType() {
                 return String.format("application/json; charset=utf-8");
             }

             @Override
             public byte[] getBody() throws AuthFailureError {
                 try {

                     return requestBody == null ? null : requestBody.getBytes("utf-8");
                 } catch (UnsupportedEncodingException uee) {

                     return null;
                 }
             }
         };
         RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
         queue.add(stringRequest);
     } catch (Exception error) {
         Toast.makeText(MainActivity.this, "Unexpected Network Error", Toast.LENGTH_LONG).show();
         error.printStackTrace();
     }
 }

1 个答案:

答案 0 :(得分:0)

要添加参数,您必须覆盖getParams(),如下所示:

 StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("Response: >", response); /// put this on the UI wil contain the percentage of accuracy if positive

                    }
                },

                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //  imageView.setVisibility(View.GONE);
                        Log.d("network", "=========>", error);
                        error.printStackTrace();
                        Toast.makeText(MainActivity.this, "Error Submitting Image", Toast.LENGTH_LONG).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String>  params = new HashMap<String, String>();
                        params.put("your-key", your-data);
                        return params;
                    }
    };