簡體   English   中英

在 Volley HTTP POST 請求中設置簡單字符串 header(不是鍵/值對)

[英]Set simple string header (not key/value pair) in Volley HTTP POST request

編輯:看起來主要問題是設置僅字符串 header 沒有鍵/值對和關聯的分隔符,因為運行手動 curl 請求沒有“=”給我一個服務器響應,因此我編輯了標題。

我正在嘗試使用 Volley 從 Android 應用程序發送一個 POST 請求以進行身份驗證,如本 Amazon Alexa 教程中所述。

對於我發送的第二個請求(需要標頭),我收到 400 服務器錯誤,表示請求錯誤。

根據教程頁面,這是請求 header 的樣子:

請求必須包含以下標頭:

 POST /auth/o2/token Host: api.amazon.com Content-Type: application/x-www-form-urlencoded

如果我對 Volley Request class 使用常規 getHeaders() 方法來覆蓋標頭,我只能設置 hashmap,這會導致以下 header 格式:

{Host=api.amazon.com, Content-Type=application/x-www-form-urlencoded}

(或{POST=/auth/o2/token, Host=api.amazon.com, Content-Type=application/x-www-form-urlencoded}如果我在第一位包含另一行)

一般來說,作為 Volley 的新手,我想知道我是否在這里遺漏了一些非常明顯的東西。 這是我發送的請求:

StringRequest tokenPoller = new StringRequest(
        Request.Method.POST,
        "https://api.amazon.com/auth/O2/token",
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("volley", response);
            }
        },
        new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("volley", "Error: " + error.getMessage());
                error.printStackTrace();
            }
        }) {

    @Override
    public String getBodyContentType() {
        return "application/x-www-form-urlencoded";
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("grant_type", "device_code");
        params.put("device_code", {{my device code from previous request}});
        params.put("user_code", {{my user code from previous request}});
        return params;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String>  headers = new HashMap<String, String>();
        headers.put("Host", "api.amazon.com");
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        return headers;
    }
};

我懷疑關於標題的某些東西是關閉的,但我真的不能把我的手指放在它上面。 我也嘗試過不覆蓋標題,但無濟於事。 任何指針將不勝感激! 謝謝!

這種情況下的 400 響應並不意味着我的請求格式不正確。 這只是服務器返回的響應代碼,其中包含與authorization_pending過程相關的所有錯誤,在我的例子中是 authentication_pending 。 由於我沒有請求錯誤消息(通過 Volley 或其他方式),所以直到很久以后我才看到。

雖然教程確實提到在輪詢令牌時可以傳遞幾種響應,但它沒有提到它們實際上是 400 響應的錯誤和錯誤描述。

我最終從 Volley 切換到 HttpsUrlConnection,並使用這個問題的響應來接收錯誤和錯誤消息作為 json 響應並實施相應的反應。

最后,我的 HTTP 請求看起來像這樣:

String stringUrl = "https://api.amazon.com/auth/o2/token";
URL url = null;

try {
    url = new URL(stringUrl);
} catch (MalformedURLException exception) {
    Log.e(TAG, "Error with creating URL", exception);
}

String response = "";
HttpsURLConnection conn = null;
HashMap<String, String> params = new HashMap<String, String>();
String scope_data = null;


try {
    params.put("grant_type", "device_code");
    params.put("device_code", mDeviceCode);
    params.put("user_code", mUserCode);
    Set set = params.entrySet();
    Iterator i = set.iterator();
    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String, String> param : params.entrySet()) {
        if (postData.length() != 0) {
            postData.append('&');
        }
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");


    conn = (HttpsURLConnection) url.openConnection();

    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.setDoOutput(true);
    conn.getOutputStream().write(postDataBytes);

    InputStream inputStream = null;

    try {
        inputStream = conn.getInputStream();
    } catch(IOException exception) {
        inputStream = conn.getErrorStream();
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder builder = new StringBuilder();

    for (String line = null; (line = reader.readLine()) != null;) {
        builder.append(line).append("\n");
    }

    reader.close();
    conn.disconnect();

    response = builder.toString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM