Android POST请求不起作用 [英] Android POST request not working

查看:96
本文介绍了Android POST请求不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在这样做:

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

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

but the request just doesn't take effect on the server... on the server I should see the data sent, but I don't see them

我也尝试过:

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

而且有效...可能是什么问题?

and it works... what could be the problem?

推荐答案

嘿,尝试使用此语法.

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

希望这会有所帮助.:)

Hope this helps. :)

这篇关于Android POST请求不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆