簡體   English   中英

Android HttpURLConnection POST RequestMethod導致400錯誤代碼

[英]Android HttpURLConnection POST RequestMethod results in 400 error code

我必須傳遞長時間的OpenStreetMaps越界API網址請求。 由於GET請求太長,我決定使用POST請求。 不幸的是,更改RequestMethod可以解決400個錯誤代碼(使用GET方法,相同的查詢結果需要200個代碼)。

這是我的HttpURLConnection代碼:

public String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        Log.wtf("JSON","connection started...");
        // Connecting to url

        urlConnection.setRequestProperty("Content-Type", "application/json");

        urlConnection.connect();
        Log.wtf("KOD",Integer.toString(urlConnection.getResponseCode()));
        // Reading data from url
        iStream = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
        StringBuilder sb = new StringBuilder();
        String line = "";
        while( ( line = br.readLine()) != null){
            sb.append(line);
        }
        data = sb.toString();
        br.close();

    }catch(Exception e){
        Log.wtf("ExceptionWhileUrlDownload", e.toString());
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}

刪除應用程序/ json

從網址中刪除查詢。 然后將該查詢字符串寫入輸出流。 之后,您可以從輸入流中讀取

HTTP錯誤400是錯誤的請求錯誤。 這意味着您發送了錯誤的請求。 當您獲得帶有GET的HTTP 200和帶有POST的HTTP 400時,您正在調用的HTTP方法是GET而不是POST。 因此,您無法將POST請求發送到GET方法。

暫無
暫無

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

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