How to set cookie in request when calling java web service from windows application using c #
How to set cookie on request when calling java web service from windows application using c #. I want to pass JSESSIONID as a cookie to HttpHeader when calling Java services. I have a JSESSIONID with me. I want to know how to create a cookie and pass it in a request.
Can someone tell me. Is it possible.
source to share
If you are using WCF to create a client proxy (svcutil.exe) you can add your own HTTP header with your request like this:
// 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();
}
If you are using wsdl.exe to build your client you can take a look here .
UPDATE:
There is really no need to send to HttpWebRequest to add a custom header:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
WebRequest request = base.GetWebRequest(uri);
request.Headers.Add("JSESSIONID", "XXXXX");
return request;
}
source to share
This answer is largely based on Darin Dimitrov's answer - if you find it helpful, please support his answer.
In my case, the web service wanted the JSESSIONID value as a cookie, not as a miscellaneous header value.
Also my WCF client was using a proxy code generated by Visual Studio Project - Set Service Reference, which I believe is the same as using the wsdl.exe program.
// 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();
}
source to share