我需要使用POST将字符串发布到服务器并获取xml响应,状态代码是正常但字符串响应总是=“”(0字节)。我的代码有什么问题吗?我从黑莓检查服务器,工作正常所以问题必须来自我的代码:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
s = NavigationContext.QueryString["parameter1"];
//string strConnectUrl = "http://www.contoso.com/example.aspx";
base.OnNavigatedTo(e);
// DoWebClient(s);
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(strConnectUrl);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
// start the asynchronous operation
httpWebRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), httpWebRequest);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
// string XML_REQUEST = "<?xml version=\"1.0\"?><mybroker"><getConnections></mybroker>";
string post = "?&track=love";
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
// Convert the string into a byte array.
byte[] postBytes = Encoding.UTF8.GetBytes(post);
// Write to the request stream.
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
static Stream str;
static string st;
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
HttpStatusCode rcode = response.StatusCode;
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
//****THIS ALWAYS RETURN "" VALUE, EXPECT TO RETURN XML STRING****
string responseString = streamRead.ReadToEnd();
//Console.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
的 的 *编辑** 代码工作,但是服务器返回参数需要在我想的Silverlight框架中不允许的&符号(&amp;),删除&amp; char服务器响应,但结果不正确。我会问一个新的问题,请参考这个Ampersand
答案 0 :(得分:1)
使用Fiddler检查过你的电话。服务器返回一个空体。您的代码工作正常。问题是服务器端。
答案 1 :(得分:0)
Fiddler说请求很好,而且响应确实是空白的。如果它是从Blackberry运行而不是从WP7运行,那么服务器是否可以进行一些用户代理检查而不返回任何内容,因为它无法识别WP7用户代理?
此外,看起来你正在发布一个查询字符串(“?&amp; track = love”),这有点不寻常。您确定在您的请求中发送的数据是正确的吗?
答案 2 :(得分:0)
帖子的价值应该是“track = love”。
我尝试过它但是响应是gzip编码的。