![](/img/trans.png)
[英]Consuming non-wcf SOAP fault from WCF client (soap fault defined)
[英]Sending GET requests from a .NET client to a non-WCF, plain XML web service
我試圖為Web服務API編寫C#客戶端( 此處的文檔 ,PDF警告)。 對API的每個請求都是一個HTTP GET調用,其參數編碼在URI中。 響應是格式正確的XML文檔,其Content-Type為“ text / xml”。 每個請求都必須包含我的API密鑰作為參數。
我可以自己實現一個Web服務代理,但是我的直覺是,有一個內置的.NET庫,由實際上有報酬來考慮這些問題的人編寫。 通過所有的搜索和閱讀,我認為我想使用WCF,但是我找不到如何將WCF用作客戶端 ,如何調用普通的XML Web服務的文檔 。 .NET或Visual Studio中有什么可以幫助我的嗎? 我不使用svcutil.exe,對嗎? 因為我正在使用的Web服務沒有任何元數據。
看一下新的HttpClient類,它是ASP.NET Web Api的一部分。 我已經成功地使用它與stackexchange API進行了對話,並且非常易於使用。
您可以使用HttpWebRequest調用Web服務API和XML庫,以將響應字符串轉換為.net對象。 這是一個簡單的示例(由於我沒有有效的密鑰,它收到一條錯誤消息“提供了無效的API訪問密鑰”):
static void Main(string[] args)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(
@"http://www.ctabustracker.com/bustime/api/v1/gettime?key=89dj2he89d8j3j3ksjhdue93j"
);
using (WebResponse resp = req.GetResponse())
{
using (Stream respStream = resp.GetResponseStream())
{
using(StreamReader reader = new StreamReader(respStream))
{
String respString = reader.ReadToEnd();
Debug.WriteLine(respString);
TestBusTimeResponse response = XmlUtil.DeserializeString<TestBusTimeResponse>(respString);
Debug.WriteLine(response.Error.Message);
}
}
}
Console.ReadLine();
}
其中XmlUtil.DeserializeString定義為:
public static T DeserializeString<T>(String content)
{
using (TextReader reader = new StringReader(content))
{
XmlSerializer s = new XmlSerializer(typeof(T));
return (T)s.Deserialize(reader);
}
}
並且TestBusTimeResponse定義為(您實際上可以使用VS附帶的xsd實用程序,使用API文檔中指定的XML模式生成此Business Object類):
[XmlRoot("error")]
public class TestBusTimeResponseError
{
[XmlElement("msg")]
public String Message
{
get;
set;
}
}
// Response in the following format:
// <?xml version="1.0"?>
// <bustime-response><error><msg>Invalid API access key supplied</msg></error></bustime-response>
[XmlRoot("bustime-response")]
public class TestBusTimeResponse
{
[XmlElement("error")]
public TestBusTimeResponseError Error
{
get;
set;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.