我得到一个例外,因为“标题有一个空值”。这是POST请求。在某些情况下,我需要将一些标头值发送为空。
这是我的代码:
private void Start()
{
try
{
this.webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(this.requestURL);
//this.webRequest.Headers[HttpRequestHeader.UserAgent] = this.userAgent;
webRequest.Headers[HttpRequestHeader.CacheControl] = "no-cache";
webRequest.Headers[HttpRequestHeader.Pragma] = "no-cache";
webRequest.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString();
webRequest.Method = "POST";
if (headers != null && headers.Count > 0)
{
webRequest.Headers["some-Header"] = "";
}
IAsyncResult result = this.webRequest.BeginGetRequestStream(new AsyncCallback(RequestCallback), webRequest);
}
catch (Exception ex)
{
}
}
void RequestCallback(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
//if (RequestBody != null)
{
using (Stream postStream = request.EndGetRequestStream(result))
{
using (var writer = new StreamWriter(postStream))
{
writer.Write(string.Empty);
writer.Flush();
postStream.Position = 0;
byte[] mArray = new byte[postStream.Length];
postStream.Read(mArray, 0, (int)postStream.Length);
}
}
}
request.BeginGetResponse(new AsyncCallback(OnRequestResponse), request);
}
private void OnRequestResponse(IAsyncResult ar)
{
try
{
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)this.webRequest.EndGetResponse(ar);
webResponseHeaders = response.Headers.GetHeaders();
System.IO.Stream responseStream = response.GetResponseStream();
}
catch (Exception ex)
{
}
}
在System.Net.HttpWebResponse的OnRequestResponse回调中获取异常response =(System.Net.HttpWebResponse)this.webRequest.EndGetResponse(ar);
答案 0 :(得分:1)
首先,尝试将您的解决方案升级到Windows Phone 8.1 有两个选项:Silverlight 8.1(您可以重用每个代码)或WP 8.1 RT(在WP和Windows 8.1之间轻松重用代码)。我建议使用Silverlight 8.1,因为您已经开发了Silverlight 8.0 App。
第二件事:回调有点老了。考虑将代码升级到Await和Async方法,因为它自然受支持
对于您的问题,请尝试使用HttpClient发送请求。这是一个代码示例:
public static async Task<string> GetHttpAsStringTask(string uriString)
{
string result;
Uri targetUri = new Uri(uriString);
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, targetUri);
//Add your empty header here
request.Headers.Add("Header name","header value");
HttpResponseMessage response = await client.SendAsync(request);
using (Stream responseStream = await response.Content.ReadAsStreamAsync())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
result = reader.ReadToEnd();
}
return result;
}
用法:
string response = await GetHttpAsStringTask("your url");
for WP 8中的等待和异步:http://developer.nokia.com/community/wiki/Asynchronous_Programming_For_Windows_Phone_8