durisvk
durisvk

Reputation: 957

Android POST request not working

I am doing this:

@Override
protected Void doInBackground(String... strings) {

    try {
        String query = "username=" + strings[0] + "&duration=" + strings[1] + "&distance=" + strings[2];
        URL url = new URL(ScoresActivity.URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        Writer writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(query);
        writer.flush();
        writer.close();
        /*conn.addRequestProperty("username", strings[0]);
        conn.addRequestProperty("duration", strings[1]);
        conn.addRequestProperty("distance", strings[2]);*/
        Log.v(TAG, strings[0] + " - " + strings[1] + " - " + strings[2]);
        //conn.connect();
    } catch(Exception e) {
        Log.e(TAG, "exception", e);
    }

    return null;
}

but the request just doesn't take effect on the server... on the server I should see the data sent, but I don't see them

I also tried this:

curl -XPOST --data "username=duri&duration=600&distance=555" http://someurl.com/

and it works... what could be the problem?

Upvotes: 4

Views: 20418

Answers (1)

Harv
Harv

Reputation: 476

hey try to use this syntax.

@Override
protected String doInBackground(String... params) {

    String urlString = params[0];
    String userName = params[1];
    String password = params[2];
    URL url = null;
    InputStream stream = null;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);

        String data = URLEncoder.encode("userName", "UTF-8")
                + "=" + URLEncoder.encode(userName, "UTF-8");

        data += "&" + URLEncoder.encode("password", "UTF-8") + "="
                + URLEncoder.encode(password, "UTF-8");

        urlConnection.connect();

        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(data);
        wr.flush();

        stream = urlConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
        String result = reader.readLine();
        return result;

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
        Log.i("Result", "SLEEP ERROR");
    }
    return null;
}

Hope this helps. :)

Upvotes: 15

Related Questions