0

I am using Retrofit2 library for http requests. It works perfectly except when I try to upload image using Multipart. I am picking an image from Gallery and setting the imageUri for an image view successfully. Then I take the image uri got from the image picker to declare a file and upload if (per some tutorials on Youtube).

This is my Retrofit interface

@Multipart
@POST("fm/upload.php")
Call<ResponseBody> callServerUrlSubmitNewOrderWithFiles(
        @Part MultipartBody.Part photo);

This is my http call function (imageUri) is the image uri got from image picker:

File originalFile = new File(image1Uri.getPath());

RequestBody filePart = RequestBody.create(

       MediaType.parse(getContentResolver().getType(image1Uri)),
       originalFile
    );

 //wrapping the file
 MultipartBody.Part file = 
   MultipartBody.Part.createFormData("photo", 
   originalFile.getName(), 
   filePart);


    //create retro instance
    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("https://mywebsite.net/")
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();

    //get client & call object for the request
    RetroFit2Calls client = retrofit.create(RetroFit2Calls.class);

    //finally, execute the request
    Call<ResponseBody> call = 
 client.callServerUrlSubmitNewOrderWithFiles(file);

 call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, 
    Response<ResponseBody> response) {
            Log.e(TAG, "onResponse: Uploaded"+ response.message() 
    );

        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) 
   {
            Log.e(TAG, "onFailure: ",t );

        }
    });

I am getting the following error (onFailure):

E/SubmitRequest: onFailure: 
okhttp3.internal.http2.ConnectionShutdownException
    at okhttp3.internal.http2.Http2Connection.newStream(Http2Connection.java:248)
    at okhttp3.internal.http2.Http2Connection.newStream(Http2Connection.java:231)
    at okhttp3.internal.http2.Http2Codec.writeRequestHeaders(Http2Codec.java:117)
    at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:50)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 

...

Here is the Manifest permissions:

   <uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Mohd Ahmed
  • 307
  • 1
  • 9

1 Answers1

1

Found the solution here: https://stackoverflow.com/a/43714729/5157228

I was missing a permission request.

Mohd Ahmed
  • 307
  • 1
  • 9