使用参数调用Web服务

时间:2018-10-08 21:37:30

标签: c# .net web-services

我必须打电话给网络服务。 该Web服务输入了两个参数,并且在输出中不返回任何内容。

您能告诉我代码(下面写的)是否正确和完整吗? 我将其插入主体中。

var httpWebRequest = (HttpWebRequest)WebRequest.Create("url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Credentials = new NetworkCredential("user", "pwd", "domain");

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = "{p1:\'Hello\'";

    string tmpjs = ",p2:\'world\'}";                       
    json = json + tmpjs;

    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

HttpWebResponse httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();

1 个答案:

答案 0 :(得分:0)

Add service reference并调用您的Web服务方法会更容易。

然后,您可以访问this之类的服务。

您的代码如下:

string json = "{p1:\'Hello\'";                              

string tmpjs = ",p2:\'world\'}";   
json = json + tmpjs;

using(YourService service = new YourService()) 
{
    service.Credentials = new NetworkCredential("user", "pwd", "domain");
    serivce.YourServiceMethod(json, param2);
}