好的,我需要消费这个网络服务,我对此一无所知,我所知道的只是它的意思:它接收一个人的国民身份证号码并返回一些有关的信息。他的xml格式。我需要在aspx页面上从C#客户端使用它。
由于我无法创建对WS的Web引用,所以我来到SO并首先询问: Unknown WebService description and consume it from C#
在那个问题上,我被建议宁愿做一个HttpClient而不是引用,所以我开始谷歌搜索并学习一些东西;现在我已经能够做到这一点:
protected void rutBTN_Click(object sender, EventArgs e) //This function triggers when the user clicks the button
{ //aside the textbox where they're meant to input the ID number
if (rutTB.Text != "") //rutTB is the textbox aside the button
{
HttpClient client = new HttpClient(); // Here i'm creating an instance of an HTTP client
var byteArray = Encoding.ASCII.GetBytes("user:password123"); //Load credentials into a byte array (censored since there should be the actual credentials)
client.BaseAddress = new Uri("http://wschsol.mideplan.cl"); //Base address of the web-service
var hResp = "mod_perl/xml/fps_by_rut?rut=" + rutTB.Text; //Creating a variable that holds the rest of the WS's URL with the ID number value added to it
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); //Server authentication header with the byte array turned into a string
client.GetAsync(hResp).ContinueWith( //Here I'm sending the GET request to the WS
(requestTask) =>
{
HttpResponseMessage resp = requestTask.Result; //This task receives the WS's http response and assigns it to a HttpResponseMessage variable called resp
try
{
resp.EnsureSuccessStatusCode(); //This line is to check that the response was successful or else throw an exception
XmlDocument xmlResp = new XmlDocument(); //Creating an instance of an xml document
resp.Content.ReadAsStringAsync<XmlDocument>().ContinueWith( //OK HERE IS WHERE I'M LOST AT, trying to take the content of the http response into my xml document instance
(readTask) =>
{
/* This is where i want to parse the xml document data obtained into some grids or something. */
});
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex.InnerException);
}
});
}
else
{
testLBL.Text = "You must enter an RUT number"; // Error label
testLBL.Visible = true;
}
}
我的VS2010强调了我失去的代码行。我知道这一行是错误的,我基于这个片段https://code.msdn.microsoft.com/introduction-to-httpclient-4a2d9cee;那个人将响应加载到JsonArray而不是XML Document。所以,如果你们能告诉我如何正确使用该代码行,以及我的功能是否有其他错误,我将非常感激。无论如何,webservice的响应是通过XML格式的浏览器发出的,所以也许我甚至不需要将它转换为xml文档?我很丢失,我还是软件开发方面的一个菜鸟,所以如果你们能帮助我,我将非常感激。
谢谢你们的帮助。
答案 0 :(得分:2)
试试这个:
XmlDocument doc;
t.Result.Content.ReadAsStreamAsync().ContinueWith(
(streamTask) =>
{
doc = new XmlDocument();
doc.Load(streamTask.Result);
});
然后,毕业于此:
var xmlStream = await t.Result.Content.ReadAsStreamAsync();
doc = new XmlDocument();
doc.Load(xmlStream);
在.NET 4.5中,使用&#34; await&#34;而不是&#34; ContinueWith&#34;如果可能的话。