I’m trying to build an Android app that talks to a .NET Web API but I’m stuck. I’ve got the server side working fine with a .NET client, but I can’t figure out how to make the Android part work.
Here’s what I’ve got on the server:
public Novel FetchNovel(int id)
{
Novel book = library.Find(id);
if (book == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return book;
}
And here’s my attempt at the Android client:
class FetchBookTask extends AsyncTask<Void, Void, List<String>> {
private static final String API_URL = "http://localhost:2757/api/novel/1";
HttpClient client = HttpClientBuilder.create().build();
@Override
protected List<String> doInBackground(Void... params) {
HttpGet request = new HttpGet(API_URL);
try {
HttpResponse response = client.execute(request);
// Process response here
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Can anyone help me figure out what I’m doing wrong? I’ve looked everywhere but can’t find a good example of how to connect an Android app to a .NET Web API. Any tips or sample code would be awesome!
hey, i’ve been there too. Retrofit is great for this! just add it to ur dependencies and create an interface for API calls. then set it up in ur activity and make the call. don’t forget internet permission in AndroidManifest.xml. if u need more help, lemme know!
For connecting an Android app to a .NET Web API, I’d recommend using Volley. It’s a robust HTTP library that simplifies network operations and is well-suited for Android development.
First, add Volley to your project dependencies. Then, create a RequestQueue and a JsonObjectRequest:
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://your-api-url/api/novel/1";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// Handle the response
Novel novel = parseNovelFromJson(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// Handle errors
}
});
queue.add(jsonObjectRequest);
This approach is efficient and integrates well with Android’s lifecycle. Remember to handle threading and UI updates appropriately.