2017-03-16 53 views
0

調用asp.net的Web API有一個Web API控制器:我如何從Android設備

// 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); 
} 

我不知道如何如何從Android的消耗這一點。請幫忙。

+0

請參閱此鏈接。 http://hintdesk.com/how-to-call-asp-net-web-api-service-from-android/ –

+0

一些更多的鏈接爲你http://square.github.io/retrofit/或http:/ /square.github.io/okhttp/或https://developer.android.com/training/volley/index.html – BNK

+0

非常感謝你 –

回答

0

我已經使用了Android HTTP Client here,發現它非常簡單易用。

然後,您可以做代碼的東西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 
    } 
}); 
0

你可以嘗試像排球庫(需要您編寫樣板代碼)或RetroFit

您可以GET和POST請求使用它們,然後再開始做閱讀POJO和模型製作。還有回調如何工作。

+0

非常感謝你。然而,我仍然無法從郵遞員打電話給PUT,你能否給我一個鏈接,謝謝。 –