Android使用JSON进行POST请求

16

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

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

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

[Android] - 使用HttpUrlConnection POST Json

使用HttpUrlConnection进行注册用户数据的POST请求

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

}

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

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

如何解决这个问题?


你能添加你的堆栈跟踪吗? - Ruben Aalders
networkonmainthreadexception 500 可能是由服务器端问题引起的。您可以检查一下服务器。 - tahsinRupam
不要再重新发明轮子了,使用asynctask毫无意义(它很糟糕),使用httpsurlconnection也没有必要(因为有更好的替代品,如okhttp/volley),手动解析json也没必要(如果可以用gson/jackson自动完成)。只需要使用Retrofit即可:http://www.vogella.com/tutorials/Retrofit/article.html - Than
获取错误代码NetworkOnMainThreadException 500。无意义。500表示不同的含义。 - greenapps
你正在发布到什么类型的服务器?请展示脚本。 - greenapps
2个回答

46

已解决:

已更改

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

4
您是否可以尝试在createMsg()方法中编写以下内容:
Thread thread = new Thread(new Runnable() {

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

thread.start(); 

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


我明天会尝试并回复。 - Cihat
https://pastebin.com/raw/FyRbkrpZ 修复了网络主线程异常。 - Foster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接