简体   繁体   中英

Android HttpURLConnection POST RequestMethod results in 400 error code

I have to pass long OpenStreetMaps overpass api url request. As it is too long for GET request I decided to use POST request. Unfortunately changing RequestMethod resolves in 400 error code (with GET method same query results in 200 code).

Here is my HttpURLConnection code:

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;
}

Remove the application/json

Remove the query from the url. Then write that query string to the output stream. After that you can read from the input stream

HTTP error 400 is bad request error. It means you are sending wrong request. As you get HTTP 200 with GET and HTTP 400 with POST, the HTTP Method that you are calling is a GET not a POST. So you can not send a POST request to a GET Method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM