Java 使用 JSON 的 Android POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42767249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:22:55  来源:igfitidea点击:

Android POST request with JSON

javaandroidjsonhttpurlconnection

提问by Cihat

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

经过研究,我仍然无法向服务器发送 JSON POST 请求。

I already tried some older answers:

我已经尝试过一些较旧的答案:

Java - sending HTTP parameters via POST method easily

Java - 通过 POST 方法轻松发送 HTTP 参数

[Android]-POST Json with HttpUrlConnection

[Android]-POST Json with HttpUrlConnection

Post request for registering user data on server by HttpUrlConnection

通过 HttpUrlConnection 在服务器上发布注册用户数据的请求

Sending json object via http post method in android

在android中通过http post方法发送json对象

How to send a JSON object over Request with Android?

如何使用 Android 通过 Request 发送 JSON 对象?

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 :

异步T.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

我收到错误代码 networkonmainthreadexception 500

How can i solve this?

我该如何解决这个问题?

采纳答案by Cihat

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)

并将代码放在一个线程中(感谢@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();
}

回答by Ravi Sanker

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

您可以尝试在 createMsg() 方法中编写此内容吗:

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.

当您在同一线程上运行网络操作时,就会出现 networkonmainthread 异常。但是,由于您使用的是异步任务,它应该可以正常工作。但是,只是为了确认。