简体   繁体   中英

How to make an Okhttp Request with “Content-type:application/x-www-form-urlencoded”?

I have an api requirement of Sending following parameters in header-

Content-Type - application/x-www-form-urlencoded

authKey- (Session token)

and following parameters in body(form day ie key-value pair)

storeId -1

type -Product

CategoryId -324

But whenever I hit this api, I am always getting 401(UnAuthorized) error. I have tried using MultipartRequest body and formBody, I know this is nothing to do with the body(Its the header where I need to send the Content-Type and authKey). Below is my code-

Request.Builder  requestBuilder = new Request.Builder();
requestBuilder.addHeader("Content-Type", "application/x-www-form-urlencoded");
    requestBuilder.addHeader("authKey",AppSharedPref.getTokenMobikul(context));
RequestBody formbody = new FormBody.Builder().add("CategoryId",bodyparms.get(0)).
                        add("type",bodyparms.get(1)).build();
 requestBuilder.post(formbody);

The Same api is giving Response with retrofit library So how to achieve this using Okhttp.

Might this will help

FormBody.Builder formBuilder = new FormBody.Builder()
    .add("key", "value");

// add more parameter as follow:
formBuilder.add("mobile", "9999999999");

RequestBody formBody = formBuilder.build();

Request request = new Request.Builder()
            .url("https://www.hittheserver.com")
            .post(formBody)
            .build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM