【问题标题】:How to make an Okhttp Request with "Content-type:application/x-www-form-urlencoded"?如何使用“Content-type:application/x-www-form-urlencoded”发出 Okhttp 请求?
【发布时间】:2018-12-17 22:26:44
【问题描述】:

我有一个在 header 中发送以下参数的 api 要求-

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

authKey-(会话令牌)

以及正文中的以下参数(形成日期,即键值对)

storeId -1

类型-产品

CategoryId -324

但是每当我点击这个 api 时,我总是会收到 401(UnAuthorized) 错误。 我尝试过使用 MultipartRequest 正文和 formBody,我知道这与正文无关(它是我需要发送 Content-Type 和 authKey 的标头)。下面是我的代码-

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 实现这一点。

【问题讨论】:

    标签: java android retrofit okhttp okhttp3


    【解决方案1】:

    这可能会有所帮助

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

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      相关资源
      最近更新 更多