2010-03-12 78 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