简体   繁体   English

如何从Android设备调用ASP.NET Web API

[英]How to call asp.net Web API from android device

I have a web api controller: 我有一个Web API控制器:

// POST: api/CountriesAPI
[ResponseType(typeof(Country))]
public async Task<IHttpActionResult> PostCountry(Country country)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.Countries.Add(country);
    await db.SaveChangesAsync();

    return CreatedAtRoute("DefaultApi", new { id = country.CountryID }, country);
}

I don't know how how to consume this from android. 我不知道如何从Android上使用它。 please help. 请帮忙。

You can try Libraries like Volley (Requires you to write boilerplate code) or RetroFit 您可以尝试Volley(需要您编写样板代码)或RetroFit之类的库

You can make get and post requests using them, do read about Pojos and model creation before you start. 您可以使用它们进行获取和发布请求,在开始之前阅读有关Pojos和模型创建的信息。 And also how do Callbacks work. 以及回调的工作方式。

I've used the Android HTTP Client available here and found it very simple and easy to use. 我使用了此处提供的Android HTTP Client,发现它非常简单易用。

You can then do a POST with code something like below: 然后,您可以使用以下代码执行POST:

public class HTTPClient 
{
    private static AsyncHttpClient client = new AsyncHttpClient();

    public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler)
    {
        client.get(url, params, responseHandler);
    }

    public static void get(String url, FileAsyncHttpResponseHandler responseHandler)
    {
        client.get(url, responseHandler);
    }

    public static void post(Context context, String url, StringEntity entity, String contentType, AsyncHttpResponseHandler responseHandler)
    {
        client.post(context, url, entity, contentType, responseHandler);
    }
}


HTTPClient.post(this, <server_url>, entity, "application/json", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response)
    {
        // Do Something
    }

    @Override
    public void onFailure(Throwable error, String content)
    {
        // Do Something else
    }
});

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

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