无法使用httpurlconnection发布参数

时间:2016-03-12 21:00:13

标签: android httpurlconnection

我使用此tutorial来使用HttpRULConnection将信息发布到服务器。以下是我的代码:

    String urlParameters = "username=" + username + "&regid=" + uuid;
    byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );

    try {
        URL url = new URL(server_uri);

        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("X-latitude", "40.7439905");
            conn.setRequestProperty("X-longitude", "-74.0323626");
            conn.setRequestProperty("charset", "utf-8");
            conn.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
            conn.setUseCaches(false);

            int responseCode = conn.getResponseCode();
            Log.d("responseCode", responseCode + "");

            //send register request
            OutputStream wr = conn.getOutputStream();
            wr.write(postData);
            wr.flush();
            wr.close();

            //get response
            .........

            Log.d("registration_id", registerResponse.registration_id+"");

        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

然而,LogCat说: content-length promised 54 bytes, but received 0。 这意味着参数未成功发布。 在我的服务器中,它还显示: username=null, uuid=null

提前感谢。

1 个答案:

答案 0 :(得分:0)

这是Volley将数据发送到服务器的方式。

首先转到Gradle并导入库。将其粘贴到dependencies中 `compile' me.neavo:volley:2014.12.09'

    private Map<String, String> data;

`

 StringRequest stringRequest = new StringRequest(Request.Method.POST, SERVER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            // puts the data (which goes to server)
            data.put("name",user_name);
            data.put("gender",user_gender);

            data.toString();
            return data;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest);

此示例发送POST,但您可以更改它并使用Request.Method.GETSERVER_URL是您发送数据的地方。 dataMap,您可以在其中放置参数。