1

I am using okhttp3 for upload image on server and i success in Upload image but i can not POST parameter with MultipartBody

my code is here..

File sourceFile = new File(sourceImageFile);

            Log.logInfo("File...::::" + sourceFile + " : " + sourceFile.exists());

            final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");


            OkHttpClient client = App.getInstance().getOkHttpClient();

            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart(KEY_ACCESS_TOKEN, accessToken)
                    .addFormDataPart(KEY_FILE, "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
                    .build();

            Request request = new Request.Builder()
                    .url(URL_IMAGE_UPLOAD)
                    .post(requestBody)
                    .build();

           Response response = client.newCall(request).execute();

I want to add "key" and "value" by POST Method in above code So how can i do.

Mansukh Ahir
  • 3,373
  • 5
  • 40
  • 66

2 Answers2

3

As I learned before, see this link https://stackoverflow.com/a/34127008/6554840

In that passed member_id with its value.

So you are passing values with KEY_ACCESS_TOKEN is must be work.

.addFormDataPart(KEY_ACCESS_TOKEN, accessToken)

will work as post parameter.

I hope it will work.

Note: Must be your Web side is working.

Community
  • 1
  • 1
Zoya
  • 51
  • 5
2

Use this you have to create HashMap<String, String> this way and add it to Builder.

These are the Imports.

import okhttp3.OkHttpClient;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;

Code:

// HashMap with Params
HashMap<String, String> params = new HashMap<>();
params.put( "Param1", "A" );
params.put( "Param2", "B" );

// Initialize Builder (not RequestBody)
FormBody.Builder builder = new FormBody.Builder();

// Add Params to Builder
for ( Map.Entry<String, String> entry : params.entrySet() ) {
    builder.add( entry.getKey(), entry.getValue() );
}

// Create RequestBody
RequestBody formBody = builder.build();

// Create Request (same)
Request request = new Request.Builder()
        .url( "url" )
        .post( formBody )
        .build();
Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95