【问题标题】:How to properly format a POST API request with JSON?如何使用 JSON 正确格式化 POST API 请求?
【发布时间】:2018-01-22 07:44:06
【问题描述】:

我自学了如何开发 Android 应用程序,最近我开始使用 Volley 库进行网络连接。我已经能够用它发送基本请求。我正在尝试使用 Pocket 的 API 来查看我的应用程序是否可以获取这些项目。他们的documentation page 提到我必须像这样发送 JSON 请求

POST /v3/oauth/request HTTP/1.1
Host: getpocket.com
Content-Type: application/json; charset=UTF-8
X-Accept: application/json
{"consumer_key":"1234-abcd1234abcd1234abcd1234",
"redirect_uri":"pocketapp1234:authorizationFinished"}

所以我在我的应用程序中创建了一个 JSONObject,将密钥 consumer_key 添加到我的使用者密钥的值中,然后在密钥 redirect_uri 中添加了其各自的值。我使用 Volley 将这个 JSONObject 作为请求发送到所需 URL 作为 POST 请求。我收到的响应代码是 403,这是由错误的消费者密钥引起的。我已经仔细检查了消费者密钥,所以问题出在我的请求上。我应该如何进行 JSON 请求?我是否必须添加额外的数据,例如 Content-Type?如果有,怎么做?

如果不是太多,您能否指出我对 JSON 的初学者友好资源,因为我对 Web 开发知之甚少? 谢谢。

【问题讨论】:

  • {"consumer_key":"1234-abcd1234abcd1234abcd1234", "redirect_uri":"pocketapp1234:authorizationFinished"} 是标题还是正文?
  • 首先,使用 curl 命令使用您的 consumer_key 执行此发布请求,确保密钥正确。其次,解析您的 JSONObject 代码。

标签: android json api android-studio


【解决方案1】:

您对代码使用什么请求方法?使用 StringRequest 方法时遇到问题。使用 JsonObjectRequest 方法时的工作。

根据我的经验,这里是创建请求的方法。

创建头参数

final Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("X-Accept", "application/json");
headers.put("consumer_key", "your-consumer-key");
headers.put("redirect_uri", "https://kamus.nusagates.com");

从标题创建JSONObject

JSONObject obj = new JSONObject(headers);

创建 JsonObjectRequest

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://getpocket.com/v3/oauth/request", obj, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
               //get all response data
                Log.d("respon", String.valueOf(response));
                try {
                    //get code from response
                    Log.d("respon code", response.getString("code"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return headers;
            }

            @Override
            protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                String server = String.valueOf(response.headers);
                Log.d("header", server);
                return super.parseNetworkResponse(response);
            }
        };

将请求添加到队列

RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(jsonObjectRequest);

希望这可以帮助您解决问题。

干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    相关资源
    最近更新 更多