Xamarin.Forms REST Web service Call - POST & GET - xamarin

I'm new to Xamarin.Forms But I'm okay with UI modules development But I need to config the Web service in the project. I preferred REST service, How can I manage rest service in Xamarin.Forms. I've existing service details from the native iOS application. Can you please help me to config the POST and GET service call in Xamarin.Forms. If you share the example of each POST and Get, It would be more helpful for me.

We have a detailed documentation to access the RESTful webservice to help you. You can find the documentation here: https://developer.xamarin.com/guides/xamarin-forms/web-services/consuming/rest/

Add HttpClient Nuget Package
And Json Package
Using below snippet to consume the REST web service.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://Host/Service.svc/");
string jsonData = #"{""Password"" : ""test#123"", ""UserId"" : ""$test#demo"", ""format"" : ""json""}";
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await client.PostAsync("login", content);
var result = response.Content.ReadAsStringAsync().Result;
if (result != "")
{
var sessionResponseJson = JsonConvert.DeserializeObject<sessionResponse>(result);
}

Related

Can a REST API be used within a Web API service?

I need to create a Web API "wrapper" that is consumed by a client, but in this Web API Service, I actually need to create a POST request to a different REST API service that is running on the same IIS server that does some work and returns StringContent that I pass back to the client via a JSON HttpResponse. Is this possible? Instead of the client making direct calls to the actual REST API and returning data they don't need/want, they would call my Web API service and I would only return them the required data. I know this was done in the old SOAP WSDL model.
If I need the client to pass in a couple parameters that are required for my POST request, would I be having the client use a GET or POST request?
This is an sample code i used call API inside another API using POST method.
using (var client = new HttpClient())
{
string query;
using (var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"username", username},
{"password", password}
}))
{
query = content.ReadAsStringAsync().Result;
}
var model = new{
username = txtUsername.Text,
password = txtPassword.Text
};
var json = JsonConvert.SerializeObject(model);
var user = new StringContent(json, Encoding.UTF8, "application/json");
using (var response = await client.PostAsync(#"http://localhost/dataagent/api/user/authenticate", user))
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
// handle result here
}
}
}

Cloud AutoML API has not been used in project 618104708054 before or it is disabled

I am trying to build a .NET small app to predict images using my model that was trianed on AutoML.
But I am getting this error:
Cloud AutoML API has not been used in project 618104708054 before or
it is disabled. Enable it by visiting
https://console.developers.google.com/apis/api/automl.googleapis.com/overview?project=618104708054
then retry. If you enabled this API recently, wait a few minutes for
the action to propagate to our systems and retry
First - this is not the project I am using.
Second - If I go to the link with my real project id - it says to me that the api is working well.
My code look like these:
public static string SendPOST(string url, string json)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", "Bearer GOOGLE_CLOUD_TOKEN");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
//var res = new JavaScriptSerializer().Deserialize<Response>(result);
//return res;
return result;
}
}
I will appriciate your help,
Thanks.
I finally succeded to make it, the only issue is that I needed to create a service account using the web console:
https://console.cloud.google.com/projectselector/iam-admin/serviceaccounts?supportedpurview=project&project=&folder=&organizationId=
And then to download the json key and push it via the gcloud command from my PC -
gcloud auth activate-service-account --key-file="[/PATH/TO/KEY/FILE.json]
I found the solution in this post:
"(403) Forbidden" when trying to send an image to my custom AutoML model via the REST API

Upload photos to Google Photos API - Error 500

I'm getting the error below while trying to upload media to Google Photos API, following the docs
This is how i retrieve my bytes array:
And this is how i make the request:
I've tried a lot of things and none of it work...
Note: I'm consuming other Google Photos API endpoints, such as Get Albums, Create Albums, Get Media and everything work as expected. The upload media is the only one i'm having trouble with.
Note 2: The token is being sent correctly.
Note 3: All the origin endpoints were configured in the google console (localhost included) so much so that other endpoints are working correctly.
Anyone can give me a light?
I am writing something similar in C# and was able to work with the photo api. My best advice is to double check headers. I hope this helps, additionally I added a postman screenshot of a successful call to the api:
public async Task<GoogleApiResponse> UploadPhoto(StorageFile photo)
{
var userInfo = UserInfoVault.GetUserInfo();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userInfo.AccessToken);
client.DefaultRequestHeaders.Add("X-Goog-Upload-File-Name", photo.DisplayName);
var fileStream = await photo.OpenAsync(FileAccessMode.Read);
var reader = new DataReader(fileStream.GetInputStreamAt(0));
await reader.LoadAsync((uint)fileStream.Size);
byte[] pixels = new byte[fileStream.Size];
reader.ReadBytes(pixels);
var httpContent = new ByteArrayContent(pixels);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
HttpResponseMessage photoResponse = client.PostAsync(ApiEdnpoints.UploadPhoto, httpContent).Result;
string strResponse = await photoResponse.Content.ReadAsStringAsync();
return null;
}
Postman screenshot of successful call to upload a photo

client.DeleteAsync - include object in body

I have an ASP.NET MVC 5 website - in C# client code I am using HttpClient.PutAsJsonAsync(path, myObject) fine to call a Json API (the API is also mine created in Web API).
client.BaseAddress = new Uri("http://mydomain");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PutAsJsonAsync("api/something", myObj);
I would like to do the same with a Delete verb. However client.DeleteAsync does not allow an object to be passed in the body. (I would like to record the reason for deletion alongside the Id of the item to delete in the URI).
Is there a way to do this?
You'll have to give up a little in terms of convenience since the higher-level DeleteAsync doesn't support a body, but it's still pretty straightforward to do it the "long way":
var request = new HttpRequestMessage {
Method = HttpMethod.Delete,
RequestUri = new Uri("http://mydomain/api/something"),
Content = new StringContent(JsonConvert.SerializeObject(myObj), Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(request);

Authentication for Google Custom Search Api

Short question:
Does anyone have a working solution authenticating with the Google Custom Search Api, post April 20th 2015?
Longer version:
I am trying to use the Google Custom Search Api to request on-demand indexing.
Before I even get started I am running into issues with Authentication.
According to the documentation you should use the ClientLogin Api to authenticate.
This Api was closed down on April 20th 2015, and it now returns 404 when you try and get a token from it.
The deprecation notice on the ClientLogin documentation states to use Oauth instead.
I have therefore tried to authenticate pretty much the same as Hossein here
I am receiving a bearer token from Google, but when I try to make a request I get a 401 with the following message
<Error>You are not authorized to access this resource. If you feel this is an error, try re-logging into your Google Account.</Error>
This is no real surprise, since there is no uptodate documentation and I am blindly stumbling along trying to find a correct solution.
My current code in C#:
private static async Task Run()
{
var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer("blablabla#developer.gserviceaccount.com")
{
Scopes = new[] { "https://www.googleapis.com/auth/cse" }
}.FromPrivateKey("-----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----\n"));
await credential.RequestAccessTokenAsync(CancellationToken.None);
var token = credential.Token;
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
var content =
new StringContent(
#"<?xml version=""1.0"" encoding=""UTF-8""?><OnDemandIndex><Pages><Page url=""http://url.com/to/be/indexed"" /></Pages></OnDemandIndex>");
content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
var result = await client.PostAsync("http://www.google.com/cse/api/{user_id}/index/{CSE_Id}", content);
var resultContent = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);
}
Does anyone have a solution running that works up against the www.google.com/cse/api/... endpoints?
Any language would be useful, just to know that it actually does work.

Resources