Android POST request with JSON

2022-09-03 08:48:22

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

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

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

[Android]-POST Json with HttpUrlConnection

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

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

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

我目前的代码是:

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);

}

异步.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;
}

我收到错误代码网络在主线程异常 500

我该如何解决这个问题?


答案 1

解决:

改变

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

os.writeBytes(jsonParam.toString());

并将代码放在一个线程中(感谢@Ravi Sanker)

工作代码:

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();
}

答案 2

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

Thread thread = new Thread(new Runnable() {

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

thread.start(); 

网络主线程异常发生在对同一线程运行网络操作时。但是,由于您使用的是异步任务,因此它应该可以正常工作。但是,只是为了确认。