我正在开发 Windows Phone 8 应用程序。我必须执行登录过程,然后发送一些数据。我通过 google chrome 的 POSTMAN 使用了服务的 url。到目前为止,一切都很好。我尝试使用 fiddler,虽然登录凭据很好,但我从服务器“无效请求”得到了答案,因为我没有设置内容类型:“application/json”。这样做之后一切正常。在我的 C# 代码中,尽管 mu 凭据有效,但我再次从服务器得到了意外的答案。我相信我没有正确设置内容类型。下面是我的代码:
public void UserAuthMethod(UserAuthMethod userAuth)
{
var request = (HttpWebRequest)WebRequest.Create("http://startaxi.punct.ro/api/init/userAuth");
request.ContentType = "application/json";
request.Headers[0] = "application/json"; //I tried to add this line but no results
var postData = JsonConvert.SerializeObject(userAuth);
var data = Encoding.Unicode.GetBytes(postData);
request.Method = "POST";
request.ContentLength = data.Length;
var responseString = request.BeginGetResponse(GetResponseCallback, request);
}
void GetResponseCallback(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
try
{
WebResponse response = request.EndGetResponse(result);
var reader = new StreamReader(response.GetResponseStream());
string result2 = reader.ReadToEnd();
}
catch (WebException e)
{
return;
}
}
}
我的代码有什么问题?任何帮助将不胜感激! 提前谢谢你:)
最佳答案
瞧答案:
public void UserAuthMethod(UserAuthMethod userAuth)
{
WebClient webclient = new WebClient();
Uri uristring = null;
uristring = new Uri("http://startaxi.punct.ro/api/init/userAuth",UriKind.Absolute);//Please replace your URL here
webclient.Headers["Content-type"] = "application/json";
//content
Dictionary<string, string> toSerialize = new Dictionary<string, string>();
toSerialize.Add("email", userAuth.Email);
toSerialize.Add("password", userAuth.Password);
string JsonStringParams = JsonConvert.SerializeObject(toSerialize);
webclient.UploadStringCompleted += wc_UploadStringCompleted;
webclient.UploadStringAsync(uristring, "POST", JsonStringParams);
}
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
//try
{
if (e.Result != null)
{
string responce = e.Result.ToString();
//To Do Your functionality
}
}
// catch
{
}
}
关于c# - 我想通过 post 方法调用服务器,但它无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26926093/