我正在尝试显示此应用从服务器接收到网络浏览器的html字符串。出于某种原因,我失败了。我能够将html字符串显示在消息框中,但我无法将其显示在Web浏览器中。我对c#很新,所以我为不必要的代码或错误道歉。还要提前感谢。
namespace Test2
{
public partial class MainPage : PhoneApplicationPage
{
private static readonly Dispatcher Dispatcher;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://127.0.0.1/examples/servlets/servlet/ReverseServlet");
request.ContentType = "application/x-www-form-urlencoded";
// Set the Method property to 'POST' to post data to the URI.
request.Method = "POST";
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
System.Diagnostics.Debug.WriteLine("Please enter the input data to be posted:");//Test code
string postData = "string is this = Testing out this app for windows 7 phone";// Test string added
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
Deployment.Current.Dispatcher.BeginInvoke(
() =>
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
WebBrowser webBrowser1 = new WebBrowser();
MessageBox.Show(responseString);//Message box displays html
webBrowser1.Visibility = Visibility.Visible;
webBrowser1.NavigateToString(responseString);//Does NOT display html string
System.Diagnostics.Debug.WriteLine(responseString+" FIXED IT");
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
//allDone.Set();
});
}
}
}
答案 0 :(得分:0)
您需要将webBrowser添加到UI。如果您的UI有一个名为ContentPanel的网格,请执行ContentPanel.Children.Add(webBrowser);
,您也可以将webBrowser直接添加到通过代码创建它的UI中。要使用字符串webBrowser.NAvigateToString(responseString);