I have a xamarin app that pull data from a webAPI. I check api address so many times and i am sure it is correct. When i debug my code i have 404 not found error from server. However when i copy and paste the URL to browser i have expected result. I couldn't figure out why my app return 404.
My Method:
public async Task<ICustomerType> GetById(int id)
{
string _token;
if (App.Current.Properties.ContainsKey("token"))
{
_token = (string)App.Current.Properties["token"];
}
else
{ _token = null; }
var webApiResponse =
_connector.PostAsync(
"api/Customer/get/id/" + id,
string.Empty, _token).Result;
var response = webApiResponse.Result.ToString();
var jObjectResponse = JObject.Parse(response);
ICustomerType customerTypeObj = null;
return customerTypeObj;
}
My bridge method to HttpClient's PostAsync method:
private async Task<TResponse> PostAsync(string requestPath, string
jsonContent, bool getToken, string token)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(_apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
if (getToken)
{
token = GetApiTokenAsync().Result;
}
if (!string.IsNullOrEmpty(token))
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
}
var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = client.PostAsync(requestPath, httpContent).Result;
var jsonData = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TResponse>(jsonData);
}
Token: Correct
API Url: Correct(I check "/" signs from debug output.They are well placed. My Api like:
https://MyApi.net/api/Personel/get/id/1)
My Error:
response {StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Request-Context:
appId=cid-v1:Some_String Server: Kestrel
Strict-Transport-Security: max-age=Some_Int Set-Cookie:
ARRAffinity=Some_String;Path=/;HttpOnly;Domain=MyDomain Date: Mon,
09 Jul 2018 07:54:19 GMT X-Powered-By: ASP.NET Content-Length: 0
}} System.Net.Http.HttpResponseMessage
your method verb in API is "GET" but you used "POST" in the client So in browser works because browser call "GET", but in the client doesn't work.
instead of :
var webApiResponse =
_connector.PostAsync(
"api/Customer/get/id/" + id,
string.Empty, _token).Result;
use :
var webApiResponse =
_connector.GetAsync(
"api/Customer/get/id/" + id,
string.Empty, _token).Result;
Related
While accessing Zoho api to get the token I'm getting the following error:
{"error":"invalid_client"}
Step 1: I'm requesting for Auth Code and the auth code is returned successfully.
This is the API I'm using.
https://accounts.zoho.com/oauth/v2/auth?scope=xxx&client_id=yyyyy&state=zzzz&response_type=code&redirect_uri=pppppp&access_type=offline
Step 2: Token Request
With the Auth Code obtained in Step-1 I'm doing a post request for the token at that time only I'm getting the below exception.
var authTokenRequestData = new
{
code= code,
client_id= _clientId,
client_secret =_clientSecret,
redirect_uri = _redirectUri,
grant_type = "authorization_code"
};
var data = new StringContent(JsonConvert.SerializeObject(authTokenRequestData), Encoding.UTF8, "application/json");
var url = "https://accounts.zoho.com/oauth/v2/token";
string result = "";
using (var client = new HttpClient())
{
var response = await client.PostAsync(url, data);
result = await response.Content.ReadAsStringAsync();
}
It's giving me the exception
{error:invalid_client}
I've verified my client_id and client_secret. It's correct only.
It's Server-Based-Application client I've registered.
Any help is highly appreciated on this.
There could be one more reason for this issue.
{"error":"invalid_client"}
Check if you're using the correct domain. (.in .com or...)
For example, you're using .in instead of .com or vice-versa
In my case when I was using .in domain but my domain was .com I was getting the same error {"error":"invalid_client"}
I was using this:
var url = "https://accounts.zoho.in/oauth/v2/token";
I replaced it as below and that solved my issue.
var url = "https://accounts.zoho.com/oauth/v2/token";
I could solve this issue by changing the request Content-Type
"Content-Type", "application/x-www-form-urlencoded"
Complete code is as follows:
string _domain = ".in"; /*Ensure you're using the correct .com or .in domain*/
var url = "https://accounts.zoho"+ _domain + "/oauth/v2/token";
string result = "";
using (var client = new HttpClient())
{
var data = new Dictionary<string, string>
{
{ "Content-Type", "application/x-www-form-urlencoded" },
{ "code", code },
{ "client_id", _clientId },
{ "client_secret", _clientSecret },
{ "redirect_uri", _redirectUri },
{ "grant_type", "authorization_code" },
{ "access_type", "offline" }
};
var response = await client.PostAsync(url, new FormUrlEncodedContent(data));
result = await response.Content.ReadAsStringAsync();
}
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");
Getting error while posting data to sql using .net Web API in xamarin.forms
StatusCode: 204, ReasonPhrase: 'No Content', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{Cache-Control: no-cache Pragma: no-cache Server: Microsoft-IIS/8.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Access-Control-Allow-Headers: Content-Type Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS Date: Thu, 17 Mar 2016 08:32:28 GMT Expires: -1 }}
this is my code to post data
T returnResult = default(T);
HttpClient client = null;
try
{
client = new HttpClient();
client.BaseAddress = new Uri(HostName);
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.Timeout = new TimeSpan(0, 0, 15);
HttpResponseMessage result = null;
StringContent data = null;
if (content != null)
// data = new StringContent(JsonConvert.SerializeObject(content), UTF8Encoding.UTF8, "application/json");
data = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");
if (method == HttpMethod.Get)
result = await client.GetAsync(endpoint);
if (method == HttpMethod.Put)
result = await client.PutAsync(endpoint, data);
if (method == HttpMethod.Delete)
result = await client.DeleteAsync(endpoint);
if (method == HttpMethod.Post)
result = await client.PostAsync(endpoint, data);
if (result != null)
{
if (result.IsSuccessStatusCode
&& result.StatusCode == System.Net.HttpStatusCode.OK)
{
var json = result.Content.ReadAsStringAsync().Result;
returnResult = JsonConvert.DeserializeObject<T>(json);
}
}
where should be the problem ?. My API is working fine and it is enabled CORS
Here is an example of how I am using PostAsync in my code, I think the error 'No Content' is referring on you are not sending anything to the server maybe? I hope this example helps:
public async Task<bool> PostAppointmet(AppointmentEntity anAppointment)
{
try{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + App.apiToken);
const string resourceUri = ApiBaseAddress + "/citas";
string postBody = JsonConvert.SerializeObject(anAppointment);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsync (resourceUri, new StringContent (postBody, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode) {
return true;
}
return false;
}
catch{
return false;
}
}
Where AppointmentEntity is my Model:
public class AppointmentEntity
{
public int doctor { get; set; }
public PatientEntity paciente { get; set; }
public DateEntity cita { get; set; }...
}
Try to use like this
var task = client.PostAsync(endpoint,content:data);
I am having a web application which is sending a request to my node.js. Node module is calling my Spring REST module.
My web application to node call is as below
$.ajax({
type : "POST",
url : "http://localhost:9090/module",
dataType : 'json',
data : msgDetails,
xhrFields : { withCredentials : true },
success : function(data) {
console.log("getInbox" + JSON.stringify(data.message));
}, error : function(data) {
alert("Error in the AJAX response." + data);
} });
my node is as below
var express = require("express"),
app = express(),
http = require("http").createServer(app);
var requestObj = require('request');
responseBody = "";
indexresponseBody = null;
app.use(express.bodyParser());
app.post('/module', function(req, res){
var tempInbox = "";
var tmp = req;
var authKey = req.body.pubKey;
var reqBody = req.body;
console.log("POST"+" - "+JSON.stringify(reqBody)+" - "+authKey);
restCMCall("http://ip:port/restmodule/controller/call", req, res,authKey,reqBody);
//res.end(JSON.stringify(body));
res.header('Content-Type', 'application/json');
//resp.header('Charset', 'utf-8');
res.send({"name1":"name"});
});
function restCMCall(resturl, req, res, authKey,reqBody){
var i = 0;
console.log("reqBody :- "+reqBody+" resturl "+resturl+" "+i++);
requestObj({
url : resturl,
method : "POST",
headers : { "Content-Type" : "application/json","pubKey":authKey},
body : JSON.stringify(reqBody)
},
function (error, resp, body) {
tempInbox = body;
console.log(resp+" inbox body :- "+" -------- "+i++);
//resp.writeHead(200, {'Content-Type':'application/json','charset':'UTF-8'});
//res.write(JSON.stringify({"hello":"xxx"}));
//res.end(JSON.stringify(body));
res.header('Content-Type', 'application/json');
//resp.header('Charset', 'utf-8');
res.send(body);
}
);
console.log(i++);
}
Till now I am able to get the response from the spring module and is able to print on node console. But when I am trying to add this response in response of request made by web application then it is not sent.
In Firefox Browser firebug it shows as
Response Headers
Connection keep-alive
Content-Length 21
Content-Type application/json
Date Mon, 07 Oct 2013 16:13:38 GMT
X-Powered-By Express
but response tab as blank.
I am using express module to call spring rest web service calls node.js.
Please let me know if I am missing anything. I have also tried using
response.json(body)
But this is also not working.
I believe you should be making the request to url : "http://localhost:9090/getInbox" because you have not created an endpoint in your Node app that matches POST: /module
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?