Android POST请求无效

时间:2016-10-08 20:50:08

标签: android

我这样做:

@Override
protected Void doInBackground(String... strings) {

    try {
        String query = "username=" + strings[0] + "&duration=" + strings[1] + "&distance=" + strings[2];
        URL url = new URL(ScoresActivity.URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        Writer writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(query);
        writer.flush();
        writer.close();
        /*conn.addRequestProperty("username", strings[0]);
        conn.addRequestProperty("duration", strings[1]);
        conn.addRequestProperty("distance", strings[2]);*/
        Log.v(TAG, strings[0] + " - " + strings[1] + " - " + strings[2]);
        //conn.connect();
    } catch(Exception e) {
        Log.e(TAG, "exception", e);
    }

    return null;
}

但是请求只是在服务器上没有生效...在服务器上我应该看到发送的数据,但是我没有看到它们

我也试过这个:

curl -XPOST --data "username=duri&duration=600&distance=555" http://someurl.com/

它有效......可能是什么问题?

1 个答案:

答案 0 :(得分:5)

嘿尝试使用这种语法。

@Override
        protected String doInBackground(String... params) {

            String urlString = params[0];
            String userName = params[1];
            String password = params[2];
            URL url = null;
            InputStream stream = null;
            HttpURLConnection urlConnection = null;
            try {
                url = new URL(urlString);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoOutput(true);

                String data = URLEncoder.encode("userName", "UTF-8")
                        + "=" + URLEncoder.encode(userName, "UTF-8");

                data += "&" + URLEncoder.encode("password", "UTF-8") + "="
                        + URLEncoder.encode(password, "UTF-8");

                urlConnection.connect();

                OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
                wr.write(data);
                wr.flush();

                stream = urlConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
                String result = reader.readLine();
                return result;

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Log.i("Result", "SLEEP ERROR");
            }
            return null;
        }

希望这会有所帮助。 :)