简体   繁体   English

服务器 - Android应用程序和服务器之间的客户端连接

[英]Server - Client connection between android app and a server

我正在开发Java服务器应用程序和Android应用程序,我的Android应用程序需要从/向服务器发送和接收数据(双向),例如我的Android应用程序需要登录到服务器,服务器需要知道谁登录在.Wich协议你建议我做这种程序吗?

Usually in this situation you can use HTTP protocol for several reason. 通常在这种情况下,您可以出于多种原因使用HTTP协议。 First of all you can reach your server even if it is behind a firewall or something like that. 首先,即使它位于防火墙之后,您也可以访问您的服务器。 Second using HTTP you can send XML or JSON data widely used in android. 其次使用HTTP,您可以发送在android中广泛使用的XML或JSON数据。 The only limitation you have is the HTTP protocol is a synchronous protocol so you send and wait for the answer. 您唯一的限制是HTTP协议是一个同步协议,因此您发送并等待答案。 Using HTTP you can use your existing server architecture and you can wrap your business layer with a Webservices so that you can expose your services. 使用HTTP,您可以使用现有的服务器体系结构,并可以使用Web服务包装业务层,以便公开服务。 If you need that server can contact your app you can use you can use Google Cloud Mesaging. 如果您需要该服务器可以联系您的应用程序,您可以使用Google Cloud Mesaging。

Use Http request (get or post request) to communicate with a server. 使用Http请求(获取或发布请求)与服务器通信。 You have to use a thread or an AsyncTask to perform your request or the execution fails from Api 11+. 您必须使用线程或AsyncTask来执行您的请求,否则Api 11+的执行将失败。 I attach an example of http request that receives an xml: 我附上一个接收xml的http请求示例:

    import org.apache.http.*;
    [..]

    public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        Log.d("XMLParser-getXmlFromUrl", "UnsupportedEncodingException");
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        Log.d("XMLParser-getXmlFromUrl", "ClientProtocolException");
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("XMLParser-getXmlFromUrl", "IOException");
        e.printStackTrace();
    }
    // return XML
    return xml;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM