Skip to main content
 首页 » 编程设计

python之将Python后端连接到Android APP

2024年10月24日31EasonJim

如何使用 python 作为使用 C# 构建的 Android 应用程序的后端? Python 后端是使用 Flask 框架编写的。 Android 应用是使用 xamarin 构建的。

请您参考如下方法:

无论您的服务器或客户端使用何种类型的技术,只要它们可以使用某种标准“协议(protocol)”相互通信即可。

有很多方法可以让双方(客户端和服务器)进行通信,例如套接字、xml、json 等。他们只需要相互理解即可。

在您的特定情况下,我建议在服务器上构建一个 REST 或 RESTful API ( https://flask-restful.readthedocs.org/en/0.3.3/),并在客户端上构建一个 REST 客户端库。

有很多方法和库可以从 C# 调用 REST API:

内置方法将使用 HttpWebRequest,如您在此 link 中所见:

private async Task<JsonValue> FetchWeatherAsync (string url) 
{ 
    // Create an HTTP web request using the URL: 
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (new Uri (url)); 
    request.ContentType = "application/json"; 
    request.Method = "GET"; 
 
    // Send the request to the server and wait for the response: 
    using (WebResponse response = await request.GetResponseAsync ()) 
    { 
        // Get a stream representation of the HTTP web response: 
        using (Stream stream = response.GetResponseStream ()) 
        { 
            // Use this stream to build a JSON document object: 
            JsonValue jsonDoc = await Task.Run (() => JsonObject.Load (stream)); 
            Console.Out.WriteLine("Response: {0}", jsonDoc.ToString ()); 
 
            // Return the JSON document: 
            return jsonDoc; 
        } 
    } 
} 

但如果您不希望您的应用到处都是废话(样板代码),我不推荐它。

辅助库可以是,例如,RESTSharp .它允许您轻松构建 REST 调用并将响应转换为您键入的对象。这是一个例子:

var client = new RestClient("http://example.com"); 
// client.Authenticator = new HttpBasicAuthenticator(username, password); 
 
var request = new RestRequest("resource/{id}", Method.POST); 
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method 
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource 
 
// easily add HTTP Headers 
request.AddHeader("header", "value"); 
 
// add files to upload (works with compatible verbs) 
request.AddFile(path); 
 
// execute the request 
RestResponse response = client.Execute(request); 
var content = response.Content; // raw content as string 
 
// or automatically deserialize result 
// return content type is sniffed but can be explicitly set via RestClient.AddHandler(); 
RestResponse<Person> response2 = client.Execute<Person>(request); 
var name = response2.Data.Name; 
 
// easy async support 
client.ExecuteAsync(request, response => { 
    Console.WriteLine(response.Content); 
}); 
 
// async with deserialization 
var asyncHandle = client.ExecuteAsync<Person>(request, response => { 
    Console.WriteLine(response.Data.Name); 
}); 
 
// abort the request on demand 
asyncHandle.Abort(); 

大家可以在google上搜索“C# REST client”自行判断。但是恕我直言,我使用过的更容易和更好的 REST 客户端代码是 Refit . 为什么?您只需一个接口(interface)即可定义 API 调用和响应。完全不需要编码!更重要的是,默认情况下,所有 API 调用都是异步的,这是移动应用程序响应所必需的。来自作者的自述文件:

public interface IGitHubApi 
{ 
    [Get("/users/{user}")] 
    Task<User> GetUser(string user); 
} 
 
var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com"); 
var octocat = await gitHubApi.GetUser("octocat"); 

我在 Xamarin Android/iOS 项目中使用过这个库,它运行良好。完全没有问题。

希望对你有帮助