这是我一段时间以来的第一次 c# 尝试,但我已经走到了这一步,也许我认为我需要一些专家的眼睛。
我不断收到标题中提到的错误。我猜我错过了什么明显的东西?
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace API_Call
{
class Program
{
static void Main(string[] args)
{
var watch = new Stopwatch();
HttpWebRequest request = HttpWebRequest.Create("http://bk-pim/Perfion/GetData.asmx") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/xml";
request.Headers.Add("SOAPAction","http://perfion.com/ExecuteQuery");
//FileInfo info = new FileInfo(@"C:UsersdcoatsDesktopmytestfile.txt");
//long size = info.Length;
//request.ContentLength = size;
using (var stream = request.GetRequestStream())
using (var writer = new StreamWriter(stream))
{
var body = WebUtility.HtmlEncode(File.ReadAllText(@"C:UsersdcoatsDesktopmytestfile.txt"));
body = "<?xml version="1.0" encoding="utf - 8"?>< soap:Envelope xmlns:soap = "http://schemas.xmlsoap.org/soap/envelope/" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema" >< soap:Body >< ExecuteQueryResponse xmlns = "http://perfion.com/" >< ExecuteQueryResult >" + body + "</ExecuteQueryResult></ ExecuteQueryResponse ></ soap:Body ></ soap:Envelope > ";
}
watch.Start();
var response = request.GetResponse(); //bombs here
watch.Stop();
response.GetResponseStream();
Console.WriteLine();
Console.ReadLine();
Console.WriteLine(watch.ElapsedMilliseconds);
Console.ReadLine();
}
}
}
您要求一种更好的方式与 Web 服务交互:
- 右键单击"解决方案资源管理器"中的"引用 ">
- 选择添加服务引用
- 输入服务所在的 URL - 示例 http://bk-pim/Perfion/GetData.asmx 或 http://www.dneonline.com/calculator.asmx
- 选择命名空间/设置其他选项
- 单击"确定">
- 创建一个客户端(我无法使用您的网络服务,因此此答案现在切换到使用DNEOnline的计算器,并选择命名空间" Calc"(:
Calc.CalculatorSoapClient sc = new Calc.CalculatorSoapClient();
- 客户端上的调用方法:
int result = sc.Add(1,2);
就是这样 - 没有套接字,没有构建XML等 - 服务引用创建一组对象和类来执行所有这些操作