16

After researches i still cant send a JSON POST request to a server.

I already tried some older answers:

Java - sending HTTP parameters via POST method easily

[Android]-POST Json with HttpUrlConnection

Post request for registering user data on server by HttpUrlConnection

Sending json object via http post method in android

How to send a JSON object over Request with Android?

My current code is:

FloatingActionButton btn_sendMsg = (FloatingActionButton) findViewById(R.id.btn_sendMsg);
    btn_sendMsg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            /*Snackbar.make(view, "Sendevorgang...", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();*/

            createMsg();
        }
    });

private void createMsg() {
    Message message = new Message(txtbox_msg.getText().toString(), "testUser");

        AsyncT asyncT = new AsyncT();
        asyncT.execute(message);

}

AsyncT.java :

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

    try {
        URL url = new URL("http://[ip]:[port]"); //in the real code, there is an ip and a port
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept","application/json");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.connect();

        JSONObject jsonParam = new JSONObject();
        jsonParam.put("uname", params[0].getUser());
        jsonParam.put("message", params[0].getMessage());
        jsonParam.put("latitude", "0");
        jsonParam.put("longitude", "0");
        jsonParam.put("id", "1");


        DataOutputStream os = new DataOutputStream(conn.getOutputStream());
        os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));

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

        Log.i("STATUS", String.valueOf(conn.getResponseCode()));
        Log.i("MSG" , conn.getResponseMessage());

        conn.disconnect();
    } catch (Exception e) {

    }


    return null;
}

I'm getting the error code networkonmainthreadexception 500

How can i solve this?

Community
  • 1
  • 1
Cihat
  • 835
  • 1
  • 7
  • 17
  • Could you add your stacktrace? – Ruben Aalders Mar 13 '17 at 15:21
  • networkonmainthreadexception 500 is may b causing because of server-side issues. You might check on to that. – tahsinRupam Mar 13 '17 at 15:23
  • Don't reinvent the wheel once again, there is no point of using asynctask (it's crap), httpsurlconnection (as there are better alternatives like okhttp/volley), manual json parsing (what for if it can be done automatically with gson/jackson). Just use retrofit: http://www.vogella.com/tutorials/Retrofit/article.html – Than Mar 13 '17 at 15:23
  • `getting the error code networkonmainthreadexception 500`. Nonsense. 500 means something different. – greenapps Mar 13 '17 at 15:32
  • You are posting to what kind of server? Please show the script. – greenapps Mar 13 '17 at 15:33

2 Answers2

46

Solved:

changed

os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));

to

os.writeBytes(jsonParam.toString());

And put the code in a thread (thanks to @Ravi Sanker)

Working code:

public void sendPost() {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(urlAdress);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                conn.setRequestProperty("Accept","application/json");
                conn.setDoOutput(true);
                conn.setDoInput(true);

                JSONObject jsonParam = new JSONObject();
                jsonParam.put("timestamp", 1488873360);
                jsonParam.put("uname", message.getUser());
                jsonParam.put("message", message.getMessage());
                jsonParam.put("latitude", 0D);
                jsonParam.put("longitude", 0D);

                Log.i("JSON", jsonParam.toString());
                DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
                os.writeBytes(jsonParam.toString());

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

                Log.i("STATUS", String.valueOf(conn.getResponseCode()));
                Log.i("MSG" , conn.getResponseMessage());

                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();
}
Cihat
  • 835
  • 1
  • 7
  • 17
4

Can you try with writing this in the createMsg() method:

Thread thread = new Thread(new Runnable() {

@Override
public void run() {
    try  {
        // The code written in doInBackground()
    } catch (Exception e) {
        e.printStackTrace();
    }
}});

thread.start(); 

The networkonmainthread exception comes when you run the network operations on the same thread. But, since you're using an async task, it should work fine. But, just to confirm.

Ravi Sanker
  • 84
  • 1
  • 5