2009-09-22 32 views
2

如何在使用c#從Windows應用程序調用java web服務時在請求中設置cookie。我想在調用java webservice時將HttpHeader中的JSESSIONID作爲cookie傳遞。我有我的JSESSIONID。我想知道如何創建一個cookie並在請求中傳遞它。如何在從Windows應用程序使用c調用java web服務時在請求中設置cookie#

有人可以建議我。這是否可行?

+0

您是否使用svcutil.exe或wsdl.exe來生成您的客戶端代理? – 2009-09-22 12:52:18

+0

我們使用wsdl.exe生成的客戶端代理。 – Rachel 2009-09-24 03:51:53

回答

4

如果您正在使用WCF生成客戶端代理(svcutil.exe的),你可以自定義HTTP標題附加您的要求是這樣的:

// MyServiceClient is the class generated by svcutil.exe which derives from 
// System.ServiceModel.ClientBase<TServiceContract> and which allows you to 
// call the web service methods 
using (var client = new MyServiceClient()) 
using (var scope = new OperationContextScope(client.InnerChannel)) 
{ 
    var httpRequestProperty = new HttpRequestMessageProperty(); 
    // Set the header value 
    httpRequestProperty.Headers.Add("JSESSIONID", "XXXXX"); 
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; 

    // Invoke the method 
    client.SomeMethod(); 
} 

如果您使用Wsdl.exe用生成客戶端你可以看看here


UPDATE:

其實沒有必要強制轉換爲HttpWebRequest的添加自定義標題:

protected override System.Net.WebRequest GetWebRequest(Uri uri) 
{ 
    WebRequest request = base.GetWebRequest(uri); 
    request.Headers.Add("JSESSIONID", "XXXXX"); 
    return request; 
} 
+0

嗨達林 感謝您的快速回復。我們正在使用wsdl.exe來生成客戶端。我們使用的是c#2003,所以在代理類本身中覆蓋了GetWebRequest方法(因爲我們在c#2003中沒有分類選項)。 我們嘗試了鏈接中給出的解決方案,但在嘗試轉換爲HttpWebRequest時遇到了IllegalCastException。 請讓我們知道如何解決這個問題。 – Rachel 2009-09-24 03:54:15

+0

客戶端是一個使用c#2003實現的Windows桌面應用程序。是否可以在請求的HttpHeader中將JESSIONID作爲cookie傳遞,同時調用java web服務。請讓我們知道,如果有一種方法來實現這一點使用c#2003. – Rachel 2009-09-24 07:09:29

+0

你可以嘗試添加標題,而不是鑄造。查看我的更新。 – 2009-09-24 07:44:30

1

這個答案在很大程度上是基於由達林季米特洛夫的答案 - 如果你發現它有用的,請upvote他的答案。

在我的情況下,Web服務希望JSESSIONID值作爲cookie,而不是雜項頭值。

另外我的WCF客戶端使用由Visual Studio的Project-Set Service Reference工具生成的代理代碼,我相信它與使用wsdl.exe程序相同。

// Session ID received from web service as response to authentication login 
    private string _sessionId; 


    // This code needed to add the session ID to the HTTP header as a JSESSIONID cookie value 
    using (MyServiceClient myServiceClient = new MyServiceClient()) 
    using (new OperationContextScope(myServiceClient.InnerChannel)) 
    { 
     HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty(); 
     httpRequestProperty.Headers.Add("Cookie", "JSESSIONID=" + _sessionId); 
     OperationContext.Current.OutgoingMessageProperties.Add(
              HttpRequestMessageProperty.Name, httpRequestProperty); 

     myServiceClient.someMethod(); 
    } 
相關問題