簡體   English   中英

如何修改我的代碼,以便我可以在post請求中添加body參數

[英]How can I modify my code so I can add a body parameter to the post request

我有一個項目,其中我有一些網址,每個網址都通向一個端點。 我通過帶有JSON的帖子請求連接到這些端點,我必須在其中插入一個參數(即:“email”:“mail@etc.com”),以便獲得一個我將放入體內的令牌我要連接的端點的下一個請求。

我嘗試使用addRequestProperty()和setRequestProperty(),我無法弄清楚是什么問題。 在日志中,似乎在嘗試發出http請求時出現內部服務器錯誤(代碼500)。

我有一個端點,我不需要傳遞任何參數,並且工作正常,提供一個“東西”列表,每個都有一個來自端點的JSON結果的id。 然后我必須接受每個id,所以當我點擊屏幕上列表中的“東西”時,另一個端點被調用,在另一個活動中提供帶有“stuff”詳細信息的結果 - 對於這個端點我需要傳遞給任何item我單擊從早期JSON結果中獲取的特定id。

private static String makeHttpRequestGetUser(URL url)throws IOException {

    String jsonResponse = "";

    if(url == null)
        return jsonResponse;

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000);
        urlConnection.setConnectTimeout(15000);
        //urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.addRequestProperty("email", "t1@gmail.com");
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();

        if(urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            Log.e(TAG, "Error response code in GetUser request: " + urlConnection.getResponseCode());
        }
    } catch (IOException e) {
        Log.e(TAG, "Problem retrieving the "stuff" JSON result.", e);
    } finally {
        if(urlConnection != null)
            urlConnection.disconnect();
        if(inputStream != null)
            inputStream.close();
    }

    return jsonResponse;
}

private static String extractTokenFromJson(String spotJSON){

    if(TextUtils.isEmpty(spotJSON))
        return null;

    String tokenValue = "";

    try {
        JSONObject baseJsonResponse = new JSONObject(spotJSON);
        JSONObject result = baseJsonResponse.getJSONObject("result");
        tokenValue = result.getString("token");

    } catch (JSONException e) {
        Log.e(TAG, "Problem parsing the token", e);
    }

    return tokenValue;
}

第一個為什么你不使用Volley(谷歌推薦)庫與你的其他API進行通信? 如果您決定將其更改為凌空,請在此處啟動: 適用於Android的Volley Library,使用VolleyWebClient之前編寫的小類更輕松,您只需將其添加到項目中即可享受。

但是為了您自己的代碼,我認為響應中的500錯誤顯示您的請求的內容類型丟失。 通常獲取令牌你可以使用表格內容類型如下:

setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

我希望它能幫助你,拯救你的一天。

暫無
暫無

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

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