2010-03-12 76 views
11

我实例化HttpWebRequest对象:使用HttpWebRequest类

HttpWebRequest httpWebRequest = 
    WebRequest.Create("http://game.stop.com/webservice/services/gameup") 
    as HttpWebRequest; 

当我“后”的数据,该服务,如何服务哪些网络方法将数据提交给?

我没有这个Web服务的代码,我只知道它是用Java编写的。

回答

13

这有点复杂,但它是完全可行的。

您必须知道您要采取的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 
+0

当试图获得响应时,出现错误,并且在该行上使用了“使用(HttpWebResponse响应=(HttpWebResponse)request.GetResponse())'所写的内容。有没有其他方法可以得到回应?说不知道,'GetResponse()'。 – 2014-02-05 02:02:36

1

不同的Web服务引擎以不同的方式将传入请求路由到特定的Web服务实现。

你说的是“web服务”,但没有指定使用SOAP。我将假设SOAP。

SOAP 1.1 specification说...

将SOAPAction HTTP请求报头字段可用于指示SOAP的HTTP请求的意图。该值是标识意图的URI。 SOAP对URI的格式或特性没有限制,或者它是可解析的。 发布SOAP HTTP请求时,HTTP客户端必须使用此头字段。

大多数Web服务引擎符合规范,因此使用SOAPAction:头。这显然只适用于SOAP-over-HTTP传输。

当不使用HTTP(比如TCP或其他)时,Web服务引擎需要回退一些东西。许多人使用邮件负载,特别是soap:envelope中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服务。

+0

添加服务引用是我在做什么,但WSE安全性头文件不是按照java服务的喜好,iam不得不手动编写头文件,所以我使用HttpWebRequest提交数据。 我试过使用“断言”,但这并不适用于我(在构建安全性标头中需要的某些标记时出现问题) – Developer 2010-03-12 19:10:26

+0

@Nick:WSE与“添加服务引用”无关。 WSE如何参与?它已经过时,除非你没有别的选择,否则不应该使用它。 – 2010-03-12 19:12:43