HttpURLConnection不提交POST数据(Android)

时间:2016-01-01 19:59:21

标签: java android network-programming httpurlconnection

我在我的Android应用程序中提交POST参数,但是,服务器没有收到任何参数(Play Framework中的request().body().asFormUrlEncoded()返回一个空的Map)。这是用于提交请求的AsyncTask代码:

private static AsyncTask<String, Void, String> register = new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... params) {
            String email = params[0], username = params[1], password = params[2];
            try {
                URL               url = new URL(REGISTER);
                HttpURLConnection conn;
                conn = (HttpURLConnection)url.openConnection();
                conn.setDoOutput(true);
                String            urlParams        = URLEncoder.encode("username=" + username + "&email=" + email + "&password=" + password, "UTF-8");
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Content-Length", String.valueOf(urlParams.length()));
                conn.connect();
                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                writer.write(urlParams);
                writer.flush();
                writer.close();

                int resp = conn.getResponseCode();
                Object content = conn.getContent();
                conn.disconnect();
                if(resp != 200)
                    return ERROR + "Bad response: " + resp + ", ";// + conn.getContent();
                return content.toString();
            } catch (IOException e) {
                System.out.println("IOException occurred: ");
                e.printStackTrace();
                return ERROR + e.getMessage();
            }
        }
    };

我计划制作更漂亮的东西,但我需要先做好这项工作。到目前为止,每个答案都提出了我已经完成的事情(例如connect(),设置Content-Length,完成后关闭Writer,得到响应)但它仍然不起作用。服务器收到连接,但正文为空,服务器返回400

1 个答案:

答案 0 :(得分:2)

您不需要设置内容长度或致电connect():这些都是自动的。但您需要通过API设置内容 type ,而不是通过请求属性。否则它会被API的默认值覆盖,这就是编码修复它的原因。