请指出我应该看的内容(库,类等)。我有一个Windows Froms桌面应用程序,被要求编写一个概念证明工具来调用网页并从中获取响应。
所以说我打http://www.example.com/getdetails.html?id=7
无论页面返回什么,我都会收到id = 7的对象的详细信息。 我应该看哪个班级/图书馆? 谢谢
PS:请不要给我有关API或SOAP或REST Web服务的示例。我没有打电话给那些。谢谢!
答案 0 :(得分:1)
您可以使用HttpWebRequest。这是一个示例:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.getdata.com/getdetails.html?id=7");
request.Method = "GET";
然后,您将获得如下响应:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
//Use the response.
}
编辑。
根据Erik的评论,HttpWebRequest已经很老了(不一定很糟糕)。我之所以经常使用它,是因为它可以提供更多控制权,完全可以满足我的日常需求,但是HttpClient和WebClient都更友好,在大多数情况下都能胜任。
答案 1 :(得分:1)
第一件事是了解您是否要调用网页或Web服务,因为网页是包含内容的html,而Web服务只是返回内容,这更有用。
如果要调用网页,请使用
using (var client = new WebClient())
{
var contents = client.DownloadString("http://www.getdata.com/getdetails.html?id=7");
Console.WriteLine(contents);
}
您可以通过多种方式调用外部服务,并且有两种类型的Web服务:1)SOAP 2)REST
使用SOAP服务的过程有点冗长,并且REST服务易于访问
要访问REST API,您可以使用以下代码
public class Class1
{
private const string URL = "https://sub.domain.com/objects.json";
private string urlParameters = "?api_key=123";
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// List data response.
HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs.
if (response.IsSuccessStatusCode)
{
// Parse the response body.
var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result; //Make sure to add a reference to System.Net.Http.Formatting.dll
foreach (var d in dataObjects)
{
Console.WriteLine("{0}", d.Name);
}
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
//Make any other calls using HttpClient here.
//Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
client.Dispose();
}
}
并调用SOAP服务,添加页面链接,该链接详细说明了这是一个漫长的过程
https://www.c-sharpcorner.com/UploadFile/0c1bb2/consuming-web-service-in-Asp-Net-web-application/