【问题标题】:Android Web Service ImplememnationAndroid Web 服务实现
【发布时间】:2011-03-15 11:46:38
【问题描述】:

我是安卓开发新手。我学东西的速度很快。

我有几个问题要在这里发帖:

  1. 我需要在 Android 中为我的登录屏幕调用 Web 服务的代码。 即当用户在登录屏幕中输入他的用户名和密码时,调用网络服务并从我的服务器检查有效用户是否有效。

  2. Android 中的 webview 也有问题。我总是得到带有“PAGE NOT FOUND”错误的 webview。

请帮助我解决我的疑问。

【问题讨论】:

    标签: android web-services


    【解决方案1】:

    1.) 我假设这个问题不涉及 WebView 问题。在您的应用程序中,您可以使用java.net.Socketjava.nio.channels.SocketChannel 创建与服务器的连接。我更喜欢 SocketChannel,因为它有一些基本 Socket 没有的特性(例如非阻塞模式)。

    使用这个类,与您的服务器通信相当容易,例如:

    // this code has not been tested (!)
    // Username and Password will be sent in a single string to the server, namely "username|password"
    String username = "foo";
    String password = "bar";
    
    // Open Socket connection to the Server example.com at Port 12345
    SocketChannel sock = SocketChannel.open(new InetSocketAddress("example.com", 12345));
    
    // send user credentials to server
    String data = username + "|" + password;
    sock.write(ByteBuffer.wrap(data.getBytes()));
    
    // await response from server
    ByteBuffer result = ByteBuffer.allocate(8); // 8 byte-large container for result
    fSocket.read(result);
    
    // The first byte of the response decides wether login failed or succeeded (just as an example!)
    if (result.get(0) == 1) {
      // login succeeded
    } else {
      // login failed
    }
    

    但是,如果您使用阻塞模式,我建议将连接处理移动到它自己的线程中。有关 Socket 通信的更多信息,请参阅 SocketSocketChannel 文档。

    2.) 如果找不到页面,可能是 URL 格式错误?一些细节在这里会有所帮助。

    【讨论】:

    • 我有问题 fSocket.read(result);你能帮助我吗。我已经导入了所有必要的库。错误是 fSocket 无法解决。请帮助我。
    • 嗯,对不起!应该是 sock.read(result),不假思索地复制了 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    相关资源
    最近更新 更多