如何使用python作为使用C#构建的Android应用程序的后端?Python后端是使用Flask框架编写的。Android应用程序是使用xamarin构建的。
无论您的服务器或客户端是否可以使用某种标准的“协议”相互通信,无论使用哪种技术。
有很多通信双方(客户端和服务器)的方法,例如套接字,xml,json等。它们只需要彼此了解即可。
在您的特定情况下,我建议在服务器上构建REST或RESTful API(https://flask-restful.readthedocs.org/en/0.3.3/),并在客户端上构建REST客户端库。
有很多方法和库可以从C#调用REST API:
内置方法将使用HttpWebRequest,如您在此链接上看到的:
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客户端”并自行判断。但是恕我直言,我曾经使用过的更容易,更好的REST客户端代码是Refit。为什么?您只需通过一个接口即可定义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项目上使用了该库,并且运行良好。完全没有问题。
希望能帮助到你
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句