使用HttpWebRequest类

14

我实例化了HttpWebRequest对象:

HttpWebRequest httpWebRequest = 
    WebRequest.Create("http://game.stop.com/webservice/services/gameup")
    as HttpWebRequest;
当我向这个服务“post”数据时,服务是如何知道将数据提交到哪个Web方法的? 我没有这个Web服务的代码,我只知道它是用Java编写的。
3个回答

19

虽然有些复杂,但完全可以做到。

您需要知道要执行的SOAPAction。如果您不知道,就无法进行请求。如果您不想手动设置,可以在Visual Studio中添加服务引用,但您需要知道服务端点。

下面的代码是手动进行SOAP请求的。

// load that XML that you want to post
// it doesn't have to load from an XML doc, this is just
// how we do it
XmlDocument doc = new XmlDocument();
doc.Load( Server.MapPath( "some_file.xml" ) );

// create the request to your URL
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( Your URL );

// add the headers
// the SOAPACtion determines what action the web service should use
// YOU MUST KNOW THIS and SET IT HERE
request.Headers.Add( "SOAPAction", YOUR SOAP ACTION );

// set the request type
// we user utf-8 but set the content type here
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Accept = "text/xml";
request.Method = "POST";

// add our body to the request
Stream stream = request.GetRequestStream();
doc.Save( stream );
stream.Close();

// get the response back
using( HttpWebResponse response = (HttpWebResponse)request.GetResponse() )
{
     // do something with the response here
}//end using

当我尝试使用你写的 using( HttpWebResponse response = (HttpWebResponse)request.GetResponse() ) 来获取响应时,出现了错误。在那一行上。有没有其他方法可以获取响应?它说 GetResponse() 不被识别。 - Solomon Closson

2
不同的 Web 服务引擎会以不同的方式将传入请求路由到特定的 Web 服务实现中。
你说了“Web 服务”,但没有具体说明使用 SOAP。我假设你是在使用 SOAP。 SOAP 1.1 规范中提到:
SOAPAction HTTP 请求头字段可以用于指示 SOAP HTTP 请求的意图。值是标识意图的 URI,SOAP 对 URI 的格式或特定性以及是否可解析都没有限制。当发出 SOAP HTTP 请求时,HTTP 客户端必须使用此头字段。
大多数 Web 服务引擎都遵守规范,因此使用 SOAPAction:头。这显然只适用于 SOAP-over-HTTP 传输。
当不使用 HTTP(例如 TCP 或其他协议)时,Web 服务引擎需要退而求其次。许多引擎使用消息有效载荷,特别是 XML 片段中的顶层元素名称。例如,引擎可能会查看这个传入消息:
<soap:Envelope
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
  soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
   <soap:Body>
       <m:GetAccountStatus xmlns:m="Some-URI">
           <acctnum>178263</acctnum>
       </m:GetAccountStatus>
   </soap:Body>
</soap:Envelope>

在编程方面,找到GetAccountStatus元素,然后根据其路由请求。

0
如果您想与Java Web服务进行通信,那么您不应该使用HttpWebRequest。您应该使用“添加服务引用”并将其指向Java服务。

我正在添加服务引用,但是Java服务不喜欢WSE安全头,所以我必须手动构建头部,然后使用HttpWebRequest提交数据。我尝试使用“断言”,但这对我没有起作用(在构建安全头中需要某些标签时出现问题)。 - Developer
@Nick:WSE与“添加服务引用”无关。WSE有什么作用?它已经过时,除非你别无选择,否则不应使用。 - John Saunders

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接