Hi I am just learning Xamarin android development and I just want to CRUD operation but I am stuck that I am unable to get any response from webapi. I have tested my api using SOAPUI and response is ok from that.
[HttpPost]
public HttpResponseMessage CreateEmpAttandance(string value)
{
if (value != "1234")
{
string json = #"{ data: 'Emp Code is not valid.'}";
var jObject = JObject.Parse(json);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
}
else
{
string json = #"{ data: 'data save sucessfully.'}";
var jObject = JObject.Parse(json);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
}
}
this is api code and below is my android application code but I am getting null response exception.
public async Task SaveTodoItemAsync(string EmpCode)
{
try
{
string url = "http://192.168.1.9/attandanceapi/api/attandance?value=12132";
var uri = new Uri(string.Format(url));
var json = JsonConvert.SerializeObject(EmpCode);
var content = new StringContent(EmpCode, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PostAsync(url, content);
var responses = response;
}
catch (Exception ex)
{
var w = ex.ToString();
}
}
I think we have problem here. You are trying to create content from string not from Json.
var content = new StringContent(EmpCode, Encoding.UTF8, "application/json");
try this:
var content = new StringContent(json, Encoding.UTF8, "application/json");
Edit:
I cannot see your default headers so if you don't have them - just add.
client.DefaultRequestHeaders.Add("Accept", "application/json");
Related
I tried using this C# code below, but getting status code 401 (reason:unautherized):
var baseUri = "https://ansibletower1.test1.com";
var data = #"{'username':'test123', 'password':'a1b2c3Z0!-99', 'description':'Ansible Api token', 'scope':'write'}";
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(baseUri);
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = httpClient.PostAsync("api/v2/tokens", content).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
var result = response.Content.ReadAsStringAsync().Result;
if (result != null)
{
return result;
}
}
}
Try-2: Using Basic Authorization header.. getting same error (401- unautherized).
I tried from python script, it works. Used Basic Authorization header in it.
var baseUri = "https://ansibletower1.test1.com";
var jsonObject = new {description = "Tower API token", scope = "write" };
var username="test123";
var password="a1b2c3Z0!-99";
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(baseUri);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes($"{username}:{password}")));
var content = new StringContent(JsonConvert.SerializeObject(jsonObject), Encoding.UTF8, "application/json");
var response = httpClient.PostAsync("api/v2/tokens", content).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
var result = response.Content.ReadAsStringAsync().Result;
if (result != null)
{
return result;
}
}
}
I figured out. The url "api/v2/tokens" is missing "/" at the end.
It should be:
var response = httpClient.PostAsync("api/v2/tokens/", content).Result;
although, i have a token xamarin gives 401 error when i post to rest api, or get..have you any solution ?
public async Task<List<Gorev>> GetGorevlerAsync(Gorev Gorev, string accessToken)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var json = JsonConvert.SerializeObject(Gorev);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string uri = Constants.BaseApiAddress + "http/GorevTeamLstStored";
var ReturnJson = await client.PostAsync(uri, content);
var ls = ReturnJson.Content.ReadAsStringAsync().Result;
var Gorevler = JsonConvert.DeserializeObject<List<Gorev>>(ls);
return Gorevler;
.
}
I have paypal integration application which receives webhook notification from paypal and I want to verify the signature as per docs:
Verify signature rest api link
Here is code which I have written:
public async Task<ActionResult> Index()
{
var stream = this.Request.InputStream;
var requestheaders = HttpContext.Request.Headers;
var reader = new StreamReader(stream);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
var webhook = serializer.Deserialize<Models.Event>(jsonReader);
var webhookSignature = new WebhookSignature();
webhookSignature.TransmissionId = requestheaders["PAYPAL-TRANSMISSION-ID"];
webhookSignature.TransmissionTime = requestheaders["PAYPAL-TRANSMISSION-TIME"];
webhookSignature.TransmissionSig = requestheaders["PAYPAL-TRANSMISSION-SIG"];
webhookSignature.WebhookId = "My actual webhookid from paypal account";
webhookSignature.CertUrl = requestheaders["PAYPAL-CERT-URL"];
webhookSignature.AuthAlgo = requestheaders["PAYPAL-AUTH-ALGO"];
webhookSignature.WebhookEvent = webhook;
var jsonStr2 = JsonConvert.SerializeObject(webhookSignature);
var result = await _webhookService.VerifyWebhookSignatureAsync(webhookSignature);
var jsonStr3 = JsonConvert.SerializeObject(result);
return Content(jsonStr3, "application/json");
}
public async Task<Models.SignatureResponse> VerifyWebhookSignatureAsync(Models.WebhookSignature webhook, CancellationToken cancellationToken = default(CancellationToken))
{
var accessTokenDetails = await this.CreateAccessTokenAsync();
_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessTokenDetails.AccessToken);
try
{
string jsonStr = JsonConvert.SerializeObject(webhook);
var content = new StringContent(jsonStr, Encoding.UTF8, "application/json");
string url = $"{_baseUrl}notifications/verify-webhook-signature";
var response = await _httpClient.PostAsync(url, content);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
throw new Exception(error);
}
string jsonContent = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<Models.SignatureResponse>(jsonContent);
}
catch (Exception ex)
{
throw new InvalidOperationException("Request to Create payment Service failed.", ex);
}
}
Webhook signature verification response :
{"verification_status":"FAILURE"}
I am getting 200K ok response from api but verification status in response is always FAILURE.I tried many different request.
I am not sure if something is wrong from my request. Looking for help.
Hello i'm doing an xamarin.form application and i'm implementing the twitter login using oauth.
I have problem to get the request_token folowing the link:
https://dev.twitter.com/oauth/reference/post/oauth/request_token
using restsharp.portable for the request POST i arrive at this point:
public async void GetTwitterToken()
{
try
{
TwitterLogin tw = new TwitterLogin();
RestClient client = new RestClient("https://api.twitter.com");
RestRequest request = new RestRequest("/oauth/request_token", Method.POST);
client.Authenticator = OAuth1Authenticator.ForRequestToken(tw.oauth_consumer_key, tw.oauth_consumer_secret);
IRestResponse response = await client.Execute(request);
}
catch (Exception e)
{
}
}
Parameter "response" it's ok but i'don't know how to parse to get token (it's not json).
i have seen this example:
public void GetRequestToken()
{
var client = new RestClient("https://api.twitter.com"); // Note NO /1
client.Authenticator = OAuth1Authenticator.ForRequestToken(
_consumerKey,
_consumerSecret,
"http://markashleybell.com" // Value for the oauth_callback parameter
);
var request = new RestRequest("/oauth/request_token", Method.POST);
var response = client.Execute(request);
var qs = HttpUtility.ParseQueryString(response.Content);
_token = qs["oauth_token"];
_tokenSecret = qs["oauth_token_secret"];
}
But i don't have HttpUtility.ParseQueryString(response.Content) whith xamarin.form framework
I am trying to POST parameters through the request, to a service that returns a JSON object. The service works well for android and iOS. I am trying to get this working for wp7. The service requires the content type to be 'application/json' I have pasted the code that sets up the http request below:
var client = new RestClient(baseurl);
var request = new RestRequest();
request.Resource = "login";
request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.AddHeader("content-type", "application/json");
request.RequestFormat = DataFormat.Json;
var postData = new Dictionary<string, string>()
{
{"key1",value1},
{"key2",value2}
};
request.AddBody(postData);
client.ExecuteAsync(request, response =>
{
var jsonUser = response.Content;
});
The response error I get from the server is an internal server error. Is anything wrong with the code above. I also tried request.AddParameter method but ended with the same result. The code for that is below:
var client = new RestClient(baseurl);
var request = new RestRequest();
request.Resource = "login";
request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.AddHeader("content-type", "application/json");
request.RequestFormat = DataFormat.Json;
var postData = new Dictionary<string, string>()
{
{"key1",value1},
{"key2",value2}
};
var json = JsonConvert.SerializeObject(postData);
request.AddParameter("application/json", json, ParameterType.RequestBody);
client.ExecuteAsync(request, response =>
{
var jsonUser = response.Content;
});
Is there anything that I am doing wrong in either of the cases?