【问题标题】:Android HttpURLConnection POST RequestMethod results in 400 error codeAndroid HttpURLConnection POST RequestMethod 导致 400 错误代码
【发布时间】:2017-09-11 10:29:58
【问题描述】:

我必须通过长 OpenStreetMaps overpass api url 请求。由于 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;
}

【问题讨论】:

  • 您应该以正常方式发布。相反,您将其设为 application/json。那是错误的。此外,您没有发布任何数据。您没有将数据写入输出流。
  • downloadUrl()我想知道你想下载什么。
  • 我删除了 application/json 行,但没有帮助。我正在尝试下载 Json OSM 响应。通过 GET 方法,整个查询都在 strUrl 中,但在少数情况下我的查询变得很长。 URL 查询如下所示:overpass-api.de/api/interpreter?data=[out:json]<long OSM 在此处查询>
  • 您没有发布任何数据!那么这怎么可能奏效呢?您没有发布那么长的 osm 查询字符串。
  • 从 url 中删除查询。然后将该查询字符串写入输出流。之后,您可以从输入流中读取。

标签: android post httpurlconnection openstreetmap urlconnection


【解决方案1】:

删除应用程序/json

从 url 中删除查询。然后将该查询字符串写入输出流。之后,您可以从输入流中读取

【讨论】:

    【解决方案2】:

    HTTP 错误 400 是错误的请求错误。这意味着您发送了错误的请求。当您使用 GET 获得 HTTP 200 和使用 POST 获得 HTTP 400 时,您调用的 HTTP 方法是 GET 而不是 POST。所以你不能向 GET 方法发送 POST 请求。

    【讨论】:

    • 感谢您的回答。据此:overpass-api.de/command_line.html OSM overpass api 支持 GET 和 POST 方法。不过,如果我的代码没问题,那么它可能不是真的......
    • 错误请求只是json方式造成的。不是因为它是一个 POST。 POST 是可能的,但应该以正确的方式完成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2020-03-18
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    相关资源
    最近更新 更多