I have to make a POST request to an ASP WEB APi 2 with OWIN login which is expecting the following body:
grant_type=password
password=qwerty
username=administrator
However, I always get FileNotFound Exception with a 400 responseCode. I'm not really sure if I'm sending the POST data the correct way. Here is my code:
public JSONObject getLoginToken(String username, String password) {
        URL url = null;
        HttpURLConnection httpURLConnection = null;
        BufferedReader bufferedReader = null;
        JSONObject response = null;
        try {
            url = new URL("someUrl");
            httpURLConnection = (HttpURLConnection) url.openConnection();
            JSONObject data = new JSONObject();
            data.put("username", username);
            data.put("password", password);
            data.put("grant_type", "password");
            httpURLConnection.setChunkedStreamingMode(0);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream os = httpURLConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(URLEncoder.encode(data.toString(), "UTF-8"));
            writer.flush();
            writer.close();
            os.close();
            httpURLConnection.connect();
            bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); // <-- fails here
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "\n");
            }
            response = new JSONObject(sb.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return response;
    }
EDIT
Here is how the endpoint is created in C#, if it's of any help.
var client = new RestClient(Statics.API_LOCATION_URL + "login");
var request = new RestRequest(Method.POST);
request.AddParameter("grant_type", "password");
request.AddParameter("username", "administrator");
request.AddParameter("password", "qwerty");
 
     
    