Search code examples
androidposthttpurlconnectionopenstreetmapurlconnection

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

Solution

  • 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