2016-11-25 137 views
1
var url = "http://domain.herokuapp.com/api/createuser"; 
var item = new { username = "kasunrt1", email = "[email protected]", password = "3333", tele = "123456789" }; 
var uri = new Uri(url); 
var json = JsonConvert.SerializeObject(item); 
var content = new StringContent(json, Encoding.UTF8, "application/json"); 
var client = new HttpClient(); 
var result = await client.PostAsync(url, content); 

该服务是向上&运行。它适用于浏览器&邮差,当我手动执行下面的API字符串。HttpClient的PostAsync失败上Xamarin.Forms(的StatusCode:404)

http://domain.herokuapp.com/api/createuser/nameTest/[email protected]/346gf4/123456789

即使下面的代码工作。

var result = await client.PostAsync("http://domain.herokuapp.com/api/createuser/nameTest/[email protected]/346gf4/123456789", null); 

结果是404 {的StatusCode:404,ReasonPhrase: '未找到',版本:1.1,内容:System.Net.Http.StreamContent,集管: { 服务器:牛仔 连接:保活 X-已启动方式:快速 X-Content-Type的选项:nosniff 日期:周五年,2016年11月25日6时27分06秒GMT 途经:1.1 vegur 内容类型:文本/ HTML;字符集= UTF-8 的Content-Length:28 }}

的Heroku仅接收下面的请求。 2016-11-25T06:31:27.827923 + 00:00 heroku [router]:at = info method = POST path =“/ api/createuser”host = domain.herokuapp.com request_id = 1cb51340-05a5-4503- acb5-9e3b45cdf393 FWD = “61.245.163.5” DYNO = web.1连接= 1ms的服务= 71个毫秒状态= 404个字节= 226

我似乎无法找到什么是错在这里。任何帮助将不胜感激。 谢谢!

+0

不能重现。我在问题 –

回答

1

有两种选择可以将数据发送到API/URL。通过url参数或POST参数。您通过邮递员发送的网址通过url参数发送参数(whats the difference?)。

另一方面,您通过POST参数发送参数PostAsync方法HttpClient。这个值在请求正文中以内容类型指定的格式发送。

HttpClient然后尝试访问的网址http://domain.herokuapp.com/api/createuser(withtout末尾的参数),而这个网址不存在,这就是为什么你会得到404错误。

选项1:更改API-方法,该值是通过POST

选项2发送:变更请求在url可变

选项来设置值1是优先停留和正确的方式来达到此目的。因为你发布了一些东西给你的api。你的值需要在request-body中,而不是直接在url中。所以改变你的API和你的代码应该工作

+0

提供的代码中得到了结果。选项1工作。感谢一堆好的解释和答案! @Joehl – Heshan

相关问题