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

半腔热情 提交于 2019-12-11 17:49:06

问题


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 i.e 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.


回答1:


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();


来源:https://stackoverflow.com/questions/51259058/how-to-make-an-okhttp-request-with-content-typeapplication-x-www-form-urlencod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!