API request returning error code 400, when i try to decode the InputStream to Bitmap before the Retrofit enqueue

68 Views Asked by At

I'm trying to send the POST API request to the Server like below and I'm getting the successful response code - 200, but when I try to decode the InputStream to Bitmap, then only the API requests get failed status code - 400, what went wrong with this approach

   InputStream inputStream = null;

                try {
                    inputStream = getContentResolver().openInputStream(imgUri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                RequestBody requestBody = RequestBodyUtil.create(MediaType.get("image/" + imgType), inputStream);
          
                RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("messaging_product", “help”)
                        .addFormDataPart("file", "image/" + imgType, requestBody)
                        .addFormDataPart("type", "image/" + imgType)
                        .build();
    
                //---#####if I remove the below line, then everything working fine #####
                Bitmap bitmap=BitmapFactory.decodeStream(inputStream);
                Log.d(TAG, "onClick: ");


                Call<ModelGraphResponse> call = RetrofitInstance.getRetrofitClient().create(IService.class).uploadImageToGraph(name, body);
             
              
                call.enqueue(new Callback<ModelGraphResponse>() {
                    @Override
                    public void onResponse(Call<ModelGraphResponse> call, retrofit2.Response<ModelGraphResponse> response) {
                        Log.d(TAG, "onResponse: ");
                        if (response.isSuccessful()) {
                           
                        } else {
                                                           }

                    }

                    @Override
                    public void onFailure(Call<ModelGraphResponse> call, Throwable t) {
                        Log.d(TAG, "onFailure: ");
                        button.setVisibility(View.VISIBLE);
                        progressBar.setVisibility(View.INVISIBLE);
                        textView.setText("Failed to Upload..");
                    }
                });
1

There are 1 best solutions below

2
Sandesh Khutal On

Try this once

URL url = new URL(//your URL//);
 try { 
HttpURLConnection connection  = (HttpURLConnection) url.openConnection();

InputStream is = connection.getInputStream();
 } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
//YOUR CODE

Bitmap img = BitmapFactory.decodeStream(is, null, options);