要使用Silverlight GET HttpWebRequest设置标头,请按照以下步骤操作:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com");
request.Method = "GET";
request.Headers["HeaderName"] = "HeaderValue";
请注意,您需要将“HeaderName”和“HeaderValue”替换为实际的标头名称和值。
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseData = reader.ReadToEnd();
response.Close();
完整的示例代码如下:
using System;
using System.IO;
using System.Net;
using System.Windows;
namespace SilverlightHttpWebRequest
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com");
request.Method = "GET";
request.Headers["HeaderName"] = "HeaderValue";
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseData = reader.ReadToEnd();
Dispatcher.BeginInvoke(() =>
{
ResultTextBlock.Text = responseData;
});
response.Close();
}
}
}
这个示例代码将使用Silverlight GET HttpWebRequest设置标头,并获取响应数据。请注意,这个示例代码使用了异步回调来处理响应,以确保在获取响应时不会阻塞UI线程。
领取专属 10元无门槛券
手把手带您无忧上云