如何使用"Content-type:application/x-www-form-urlencoded"发出Okhttp请求? [英] How to make an Okhttp Request with "Content-type:application/x-www-form-urlencoded"?
问题描述
我有一个在标头中发送以下参数的api要求-
I have an api requirement of Sending following parameters in header-
Content-Type-应用程序/x-www-form-urlencoded
Content-Type - application/x-www-form-urlencoded
authKey-(会话令牌)
authKey- (Session token)
以及正文中的以下参数(表单日期,即键值对)
and following parameters in body(form day i.e key-value pair)
storeId -1
storeId -1
类型-产品
CategoryId -324
CategoryId -324
但是,每当我按下此api时,我总是会收到401(UnAuthorized)错误. 我尝试使用MultipartRequest正文和formBody,我知道这与正文无关(它是我需要发送Content-Type和authKey的标头).下面是我的代码-
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);
同一个api通过改造库提供响应,因此如何使用Okhttp实现.
The Same api is giving Response with retrofit library So how to achieve this using Okhttp.
推荐答案
这可能会有所帮助
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();
这篇关于如何使用"Content-type:application/x-www-form-urlencoded"发出Okhttp请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!