繁体   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