【问题标题】:android, how to send username and password to webservice as header fields?android,如何将用户名和密码作为标题字段发送到webservice?
【发布时间】:2012-03-08 19:53:46
【问题描述】:

我正在尝试在 android 手机上创建一个应用程序,该应用程序从用户那里获取用户名和密码,使用 md5 加密密码,然后使用这些参数连接到 url。

连接代码在 iphone 上运行良好,但我在 android 中找不到类似的东西:

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:myURL];

[request setHTTPMethod:@"GET"];

[request addValue:usernameField.text forHTTPHeaderField:@"UserName"];

[request addValue:MD5Pass2 forHTTPHeaderField:@"Password"];

我尝试通过 httpurlconnection 连接使用 post/get Dataoutputstream,httpclient 发送参数 httpget/httppost,但没有成功。

我想我需要将参数作为 headerfield 发送,但我不知道如何。

注意:我比较了加密结果,结果是正确的。

【问题讨论】:

    标签: android http-headers httpclient httpurlconnection


    【解决方案1】:

    我发现 Apache 库在 HTTP 方面要简单得多。

    一个例子如下:

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet();
    request.setURI(new URI("http://www.internet.com/api"));
    

    通常对于 GET 请求,您会使用 GET 参数,即将它们附加到 URL 的末尾,如下所示:

    String url = "http://www.internet.com/api?UserName=YourUsername&Password=yourpassword" 
    request.setURI(new URI(url));
    

    但既然你指定了你希望它们作为标题,你可以:

    request.addHeader("UserName", username);
    request.addHeader("Password", password);
    

    然后:

    HttpResponse response = client.execute(request);
    //Parse the response from the input stream object inside the HttpResponse
    

    【讨论】:

    • 谢谢你,你的回答清晰而全面,我试过了,虽然我认为它会工作(理论上它必须)但它没有,我仍然得到相同的结果“登录失败” !
    • 我终于找到了错误,他们给了我一个错误的用户名!现在它正在工作,谢谢。
    【解决方案2】:

    【讨论】:

    • 感谢您的回答,我尝试了您的解决方案,但结果与以前相同! “登录失败”虽然我确定参数是正确的!
    • 现在可以正常工作了,修正数据后,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-07-12
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 2019-06-29
    • 2012-06-11
    • 2012-10-20
    相关资源
    最近更新 更多