Unable to solve POST request in Android

Viewed 42

I know people have asked this question many times. But still It is causing me difficulty.

After gathering codes from a few places : like Tutorial I could write this.

What I have done : I have checked the working of the code on the GET request. It's working.

private class Myworker extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL("myurl");
            org.json.JSONObject df = new org.json.JSONObject();
            df.put("amount", "50");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            try {
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(df));

                writer.flush();
                writer.close();
                os.close();

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line).append("\n");
                    }
                    bufferedReader.close();
                    System.out.println("n " + new String(stringBuilder));
                }
            } finally {
                conn.disconnect();
            }
        } catch (Exception e) {
            System.out.println("Unable *******");
            e.printStackTrace();
        }
        return null;
    }
}

    public String getPostDataString(org.json.JSONObject params) throws Exception {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator itr = params.keys();

        while (itr.hasNext()) {
            String key = (String) itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));
        }
        return result.toString();
    }
}

Error: int responseCode=conn.getResponseCode() is also being returned as 415.

D/NetworkSecurityConfig: No Network Security Config specified, using platform default

Please help

1 Answers

A 415 is Unsupported Media Type, which is probably due to you not properly setting the Content-Type header.

Try adding

conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

In the future you may want to try a http client library such as apache httpcomponents or google-http-client as they are easier to work with.

Related