我使用 WebBrowser.Navigate()
发布到网站的 JSON 响应 URL。
一切顺利,包括正在调用的 webBrowser1_DocumentCompleted()
事件处理程序。
但是我没有得到可以编程处理的“安静”响应(例如 webBrowser1.Document
),而是收到一个文件下载对话框:
如果我单击 Save
按钮并稍后检查该文件,它包含我期望的 JSON 响应。
但我希望程序在代码中捕获此 JSON 响应,而不显示该对话框并且不必单击 Save
按钮。
如何使用 WebBrowser 控件捕获 JSON 响应?
注意: 在发布这个问题之前,我搜索了 SO,我发现的只是一个类似的问题,接受的答案并没有真正解释如何做到这一点(我已经处理了 webBrowser1_DocumentCompleted ).有什么建议吗?
更新:到目前为止,关于使用 WebBrowser 控件获取 JSON 响应,我的所有搜索都没有结果。也许我正在接近这个完全错误的?我错过了什么?
最佳答案
不要使用 WebBrowser
进行 JSON 通信。使用 WebRequest相反:
//
// EXAMPLE OF LOGIN REQUEST
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://getting-started.postaffiliatepro.com/scripts/server.php");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
//WRITE JSON DATA TO VARIABLE D
string postData = "D={\"requests\":[{\"C\":\"Gpf_Auth_Service\", \"M\":\"authenticate\", \"fields\":[[\"name\",\"value\"],[\"Id\",\"\"],[\"username\",\"user@example.com\"],[\"password\",\"ab9ce908\"],[\"rememberMe\",\"Y\"],[\"language\",\"en-US\"],[\"roleType\",\"M\"]]}], \"C\":\"Gpf_Rpc_Server\", \"M\":\"run\"}";
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();
// Display the status.
// 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.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
}
}
您可以在此 C# .NET communication with API article 中找到更多详细信息和 this thread .
关于c# - 如何使用 WebBrowser 控件捕获 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13021709/