【发布时间】:2014-02-24 07:26:54
【问题描述】:
我正在 Xamarin 中开发一个跨平台的 android 应用程序。我想发送一个注册我的设备的请求。我正在发送我的 DeviceId、DeviceName 和 EncodedAccountName,即我的电子邮件 ID。
但我没有得到任何回应。我已经在Postman 上测试了请求并得到了正确的响应。
这是我的代码:
StringBuilder registerContent = new StringBuilder();
registerContent.Append("DeviceId=").Append(deviceId).Append("&");
registerContent.Append("Name=").Append(deviceName).Append("&");
registerContent.Append("EncodedAccountName=").Append(username);
WebRequest request = WebRequest.Create(EndPoints.RegisterDeviceEndPoint);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = registerContent.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType= "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();// Dont get any response here
// Display the status.
System.Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
System.Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return response.ToString();
关于我可能会出错的任何想法?
谢谢
【问题讨论】:
-
“没有得到任何回应”是什么意思?它是否返回空引用?它根本不回来吗?它是否返回没有内容的响应?
-
@JonSkeet 是的,它给了我一个 `null
-
看起来您正在创建一个 GET 方法,而不是一个 POST。试试 Yoav 的版本,因为它应该会更好。
标签: c# android httpwebrequest xamarin