【问题标题】:HTTP Post EncodingHTTP 后编码
【发布时间】:2012-01-16 10:59:15
【问题描述】:

我想做什么


大家好,

我尝试为我的服务器创建一个登录名,以便我可以通过我的应用程序访问其中的数据。为此,我创建了一个名为 'public void doLogin(final String username, final String password)' 的 Methode。在这个 Methode 中,我启动了一个线程,在其中我将用户名和密码发布到我的服务器。现在问题开始了。当我发布帖子时,我的服务器无法处理我的帖子,如下所示:'"username="+username+"&password="+password'

为了尝试它是否是服务器端问题(实际上不是),我使用相同的参数在'curl -d' 上发了一个帖子,我得到了没有任何问题的响应。

供您参考,服务器在 Ruby3 上运行

问题


我需要如何将我的帖子更改为可以处理我发送的数据的服务器。顺便说一句,我发布的字符串一定是这样的:'"username="+username+"&password="+password //this means username=LEUSER&password=LEPASS'

请告诉我我需要更改什么,一些代码 sn-ps 或教程会很棒。在这里,您可以找到 doLogin 方法的导入代码n-ps

代码


public void doLogin(final String username, final String password) {

        Thread t = new Thread() {
            public void run() {

                String URL = "http://192.168.110.126:3000/sessions.json"; //für momentane testzwecke

                DefaultHttpClient client = new DefaultHttpClient();
                HttpResponse response;

                try {
                    HttpPost post = new HttpPost(URL);
                    StringEntity se = new StringEntity("username="+username+"&password="+password);
                    post.setEntity(se);

                    response = client.execute(post);

                    if (response != null) {

                    //response handling
                        handler.sendEmptyMessage(0);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("DataHandler", "URLConnection-Error" + e);
                }

            }

        };
        t.start();
    }

请在这方面指导我。

【问题讨论】:

  • 请通过这个:androidsnippets.com/…
  • 如果我有一个 Rails 应用程序作为测试服务器,我会在 JavaScript 中使用 $.post() 对其进行测试,然后使用 Firebug 或 Chrome 的调试工具检查 POST(标头和实体)。

标签: android ruby-on-rails-3.1 http-headers http-post


【解决方案1】:

您的代码看起来像是在发送一个 html 表单。实际上,如果您使用 -d 选项,curl 会在 http 标头中添加一个内容类型(值为 application/x-www-form-urlencoded)。

所以尝试像这样添加标题字段:

HttpPost post = new HttpPost(URL);
post.addHeader("Content-Type","application/x-www-form-urlencoded");
...

【讨论】:

    【解决方案2】:

    您需要更改的是字符串实体部分。您应该更改以下内容;

    ArrayList<NameValuePair> requestParameters = new ArrayList<NameValuePair>();    
    requestParameters.add(new BasicNameValuePair("username", username));
    requestParameters.add(new BasicNameValuePair("password", password));
    

    用户名和密码是在程序中输入的变量。

    最后,如果您忘记设置权限,它也将不起作用。你需要设置android.permission.INTERNET

    【讨论】:

    • 就像我说的那样,我得到了响应并设置了权限。
    • 也许主线程在你的 doLogin 函数之前完成。你可能需要加入他们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 2012-11-05
    • 2015-01-12
    • 2013-08-07
    相关资源
    最近更新 更多