【问题标题】:How to make a POST request by passing a object in Okhttp?如何通过在 Okhttp 中传递对象来发出 POST 请求?
【发布时间】:2018-05-28 10:22:46
【问题描述】:

这是我的 Json 身体:

{
    "username": {
        "country": "IN", 
        "number": "9620494812"
    }, 
    "password": "119209"
}

我正在尝试使用Okhttp 发出 POST 请求,如下所示:

Username username = new Username("IN" , "9620494812");

JSONObject postData = new JSONObject();

try {
    postData.put("username" , username);
    postData.put("password" , "119209");

} catch (JSONException e) {
    e.printStackTrace();
}

RequestBody body = RequestBody.create(MEDIA_TYPE , postData.toString());

Request request = new Request.Builder().url("https://www.gruppie.in/api/v1/login")
        .method("POST" , body).build();

我已经检查了请求,但我仍然收到错误

回复是:

{"status":401,"type":"about:blank","title":"Unauthorized"}

我在这里做错了什么?

【问题讨论】:

标签: java android json http-post okhttp


【解决方案1】:

根据您的 JSON,您必须像这样发送 JSON 请求。试试这个

    JSONObject postData = new JSONObject();
    JSONObject userJson=new JSONObject();
    try {
        userJson.put("country","IN");
        userJson.put("number","9620494812");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    try {
        postData.put("username" , userJson);
        postData.put("password" , "119209");

    } catch (JSONException e) {
        e.printStackTrace();
    }

【讨论】:

  • 感谢您的回答...现在工作正常...我在代码中犯了什么错误?
猜你喜欢
  • 2014-06-20
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
  • 2017-03-24
  • 2023-02-10
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
相关资源
最近更新 更多