How to send GET request in Retrofit ?(It gives error) - retrofit

I'm new at Retofit. I try to request the server but my app is craching. So, I dont know what's the problem. Below you can see my code:
if(retrofit==null){
retrofit=new Retrofit.Builder()
.baseUrl(Base_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient().newBuilder()
.connectTimeout(40, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.build())
.build();
}
return retrofit;
#GET("api.php")
Call<List<MyModel>> getLikersPost(#Field("id") String id);

You can't use #Field parameter with #GET request. Instead you must use #Query parameter.

Now my code worked:
#GET("api.php")
Call> getLikersPost(#Query("id") String id);

Related

DisplayAlert not working in a function in xamarin

I am making a get request to api and it is giving me correct results! Parameters are passed to it and they are used in get request !
If parameters I passed are correct then "Authentication is Sucessfull is printed after get call !" However if Parameters are not correctly passed Application is crashing !
Invalid Credentials Alert is not getting printed ! What I am doing wrong ?
async void Call(parameters)
{
string Url="xxx Api Url?parameters";
HttpClient client = new HttpClient();
string response = await client.GetStringAsync(Url);
if(response.Equals("200"))
{
await DisplayAlert("Alert", "Authentication is Successful", "Ok");
}
else
{
await DisplayAlert("Alert", "Invalid Credentials Added", "Ok");
}
}
Since this is happening inside an async method your Display Alert must need to be called on UI thread.
Device.BeginInvokeOnMainThread(async()=>{
await DisplayAlert("Alert", "Authentication is Successful", "Ok");
});
Also, your method seems to be an async void, it is generally advised as a bad practice to have an async void unless it is a lifecycle method or an event, You should consider using Threading Tasks instead i.e. async Task Call(parameters).
A Microsoft blog for best practices with async-await can be found here: https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming
string response = await client.GetStringAsync(Url); is most likely raising an exception when parameters is incorrect.
An uncaught exception will always crash your application.
For instance,
HttpClient client = new HttpClient();
var response = await client.GetStringAsync("https://jsonplaceholder.typicode.com/posts/1"); // works perfectly fine.
var response2 = await client.GetStringAsync("https://jsonplaceholder.typicode.com/posts/1fdqsfdqsfdqs"); //Throws a HttpRequestException because it is not found
In your case,
await DisplayAlert("Alert", "Invalid Credentials Added", "Ok");
Should be inside the block of a try {..} catch(xx) statement

How do I make a http request from an asp.net middleware?

I have a middleware which needs to call off to an external service to check for some state and then act on it. I'm wondering how I go about making a request from middleware?
I've seen some docs about having a HttpClientFactory service, but I'm not really sure how I make that available to my middleware?
You can use the default HttpClient
This allows you to create a client in your middleware and send any request you need.
Example:
using(var client = new HttpClient()){
try
{
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
// string responseBody = await client.GetStringAsync(uri);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}

GetAsync and PostAsJsonAsync methods passing parameters JsonReaderException error

I am trying to build a client side of making requests. So i do not know how i pass parameters on GetAsync method. The same problem on PostAsJsonAsync method.
Here is my code:
public static async Task<List<Users>> GetUsers(HttpClient client, Users users, string accessToken)
{
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await client.GetAsync("/api/2.0/users/?id=5&name=name");
response.EnsureSuccessStatusCode();
List<Users> listUsers= await response.Content.ReadAsAsync<List<Users>>();
Console.WriteLine("Returned list.");
return listUsers;
}
catch (HttpRequestException e)
{
Console.WriteLine("{0}", e.Message);
Console.ReadLine();
throw;
}
}
When i make this request from postman i get the results that i want. The Users class has more variables than the 2 that i request.
GetAsync without parameters works fine. When i run the project i get the error "JsonReaderException: Input string '100.0' is not a valid integer"
Is there another option to pass arguments on url?
I changed the int type of that integer property to float and the problem solved.

Get Html response with Retrofit

I'm new to Retrofit. I make a POST request to a website. Website returns response as HTML. So I will parse it. However Retrofit try to parse it as JSON. How can do it?
#FormUrlEncoded
#POST("/login.php?action=login")
void postCredentials(#Field("username") String username,
#Field("password") String password);
Should I use a callback?
Retrofit uses a converter to process responses from endpoints and requests as well. By default, Retrofit uses GsonConverter, which encoded JSON responses to Java objects using the gson library. You can override that to supply your own converter when constructing your Retrofit instance.
The interface you need to implement is available here (github.com). Here's a short tutorial as well, although for using Jackson library, many bits are still relevant: futurestud.io/blog
Also note that the converter works both ways, converting requests and responses. Since you want HTML parsing in one direction only, you may want to use GsonConverter in your custom converter, to convert outgoing Java objects to JSON, in the toBody method.
May be not the best solution but this how i managed to get the source of an html page with retrofit:
MainActivity.java
ApiInterface apiService = ApiClient.getClient(context).create(ApiInterface.class);
//Because synchrone in the main thread, i don't respect myself :p
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//Execution of the call
Call<ResponseBody> call = apiService.url();
response = call.execute();
//Decode the response text/html (gzip encoded)
ByteArrayInputStream bais = new ByteArrayInputStream(((ResponseBody)response.body()).bytes());
GZIPInputStream gzis = new GZIPInputStream(bais);
InputStreamReader reader = new InputStreamReader(gzis);
BufferedReader in = new BufferedReader(reader);
String readed;
while ((readed = in.readLine()) != null) {
System.out.println(readed); //Log the result
}
ApiInterface.java
#GET("/")
Call<ResponseBody> url();
ApiClient.java
public static final String BASE_URL = "https://www.google.com";
private static Retrofit retrofit = null;
public static Retrofit getClient(Context context) {
if (retrofit==null) {
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.client(okHttpClient)
.build();
}
return retrofit;
}

HttpClient Task was cancelled

I am trying to use HttpClient to asynchronously log a message to a REST service using the code below:
public void LogMessage(string operationURI, string message, EventLogEntryType logEntryType)
{
using (var client = new HttpClient())
{
var cancellationToken = new CancellationToken();
client.SendAsync(GetRequest(operationURI), cancellationToken).ContinueWith(
cw =>
{
var response = cw.Result; //(I get an error on this line)
if (!response.IsSuccessStatusCode)
{
LogMessageLocal(message, logEntryType);
}
});
}
}
Note: The GetRequestMessage returns an HttpRequestMessage.
But I get an error stating 'A task was canceled.'
Any ideas?
I believe this can occur when the timeout is exceeded. You might check your timeout, and log how long it was outstanding before the exception to see if it is being exceeded.
The HttpClient is disposed before SendAsync finishes. This causes a TaskCanceledException to be thrown.
Add async keyword to LogMessage.
Add await keyword to SendAsync and set its result to var response.
Do whatever you want to do with the response after awaiting it.

Resources