Consuming java web service getting error - c#

I am getting error while consuming java web service in my win form application
The error is
You must provide a request body if you set ContentLength>0 or
SendChunked==true. Do this by calling [Begin]GetRequestStream before
[Begin]GetResponse.
My code to consume java service
public byte[] StringToByteArray(string stringData)
{
System.Text.UTF8Encoding Encoding = new System.Text.UTF8Encoding();
return Encoding.GetBytes(stringData);
}
private void button1_Click(object sender, EventArgs e)
{
string DATA = #"<RepositoryType>117</RepositoryType>
<RepositoryCategory>0</RepositoryCategory>
<ModifiedBy>2825</ModifiedBy>
<ReferenceCode>0</ReferenceCode>
<FromDate>2015-10-14T11:50:00</FromDate>
<ToDate>2015-10-14T11:51:00</ToDate>
<RepositoryName>ashok</RepositoryName>
<RepositoryShortName>kumar</RepositoryShortName>
<RepositoryDesc>nothing</RepositoryDesc>
<Fixed>F</Fixed>
<IsValid>true</IsValid>
<lstVisa />
<SortOrder>0</SortOrder>
</Repository>";`
byte[] postdata = null;
HttpWebRequest _WebRequest = null;
HttpWebResponse webresponse = null;
StreamReader ResponseStream = null;
string sReturnVal = string.Empty;
string
serviceAddress="http://172.16.12.21:8888/XML_RESPONSE/rest/test/xmltest/";
try
{
_WebRequest = (HttpWebRequest)WebRequest.Create(serviceAddress + "/" + DATA);
postdata = StringToByteArray(DATA);
if (_WebRequest != null)
{
if (postdata!=null)
{
_WebRequest.Method = "POST";
_WebRequest.ContentType= "text/xml";
_WebRequest.ContentLength = postdata.Length;
_WebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
_WebRequest.SendChunked = true;
}
**webresponse = (HttpWebResponse)_WebRequest.GetResponse();**
{
if (webresponse.Headers.Get("Content-Encoding") != null && webresponse.Headers.Get("Content-Encoding").ToLower() == "gzip")
ResponseStream = new StreamReader(new GZipStream(webresponse.GetResponseStream(), CompressionMode.Decompress));
else
{
Encoding enc = System.Text.Encoding.GetEncoding(1252);
ResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
}
if (ResponseStream != null)
{
XElement Root = XElement.Load(ResponseStream);
sReturnVal = Root.Value;
}
}
}
else
{
throw new Exception("Connection to " + " Service could not be Established.",
new Exception("Please Check whether " +
" Service is running Or Contact your System Administrator."));
}
}
catch(Exception ex)
{
}
}
the highlighted line is getting error.
Please help in this.

You're adding the data to the URL instead of posting it as the request body. Take a look at this question for working code you can use: HTTP POST using web service. With ASP.NET webservices you must set the SOAPAction HTTP header, you can skip this line if your service doesn't require it.

Related

Passing C# Web service Parameters to PHP Application

I am trying to passing C# Web service Parameters to PHP Application but not getting below is my code. Actually I am passing username and password xml format because no buddy should not see that credential while passing.
Below is my C# Web service using asp.net web form button click to redirect PHP application.
[WebMethod]
public string POSTXml(string username, string password)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
StringBuilder strRequest = new StringBuilder();
string url = "http://xyz.in/getuser.php/";
req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/xml";
StreamWriter writer = new StreamWriter(req.GetRequestStream());
writer.WriteLine(username,password);
writer.Close();
rsp = req.GetResponse();
var sr = new StreamReader(rsp.GetResponseStream());
string responseText = sr.ReadToEnd();
return responseText;
}
catch (Exception e)
{
throw new Exception("There was a problem sending the message");
}
}
Below is my button click code.
protected void Button2_Click(object sender, EventArgs e)
{
localhost.WebService objserv1 = new localhost.WebService();
Label.Text = objserv1.POSTXml("nagapavani", "tech#1234");
}
Actually when user will button click passing some values to web service and through web service want to pass that value to php application. Is there Other way to achieve that requirement. When I am going to button click not going to redirect and taken this code from google.
You could send the data as following. Convert it to a byte array and write it to the request stream:
[WebMethod]
public string POSTXml(string username, string password)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
string data = "user=" + username + "&password=" + password;
string url = "http://xyz.in/getuser.php/";
byte[] buffer = Encoding.ASCII.GetBytes(data);
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
using (Stream PostData = WebReq.GetRequestStream())
{
PostData.Write(buffer, 0, buffer.Length);
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
using (Stream stream = WebResp.GetResponseStream())
{
using (StreamReader strReader = new StreamReader(stream))
{
return strReader.ReadToEnd();
}
}
WebResp.Close();
}
}
catch (Exception e)
{
throw new Exception("There was a problem sending the message");
}
return String.Empty;
}

"The underlying connection was closed: The connection was closed unexpectedly." on certain systems

I have a client application which communicates to a central server through web services (python based web service). I am currently using post method to send data. This fails on certain systems while works on most other.
here is the code
//method with post
private bool sendDataToServicePost1 (string url,string data)
{
try
{
string boundary = Guid.NewGuid().ToString().Replace("-", "");
string newLine = "\r\n";
// create cookie
Cookie sessionCookie = new Cookie();
sessionCookie.HttpOnly = true;
sessionCookie.Domain = App.ServerIP;
sessionCookie.Name = "session_id";
sessionCookie.Value = App.SessionId;
// open HTTP web request
HttpWebRequest _webRequest = (HttpWebRequest)WebRequest.Create(url);
// add cookie to request
_webRequest.CookieContainer = new CookieContainer();
_webRequest.CookieContainer.Add(sessionCookie);
//setup POST params
_webRequest.Method = "POST";
_webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
_webRequest.Timeout = 600000;
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
sw.Write(string.Format(sendFormat, boundary, newLine, "Data", data));
sw.Write("--{0}--{1}", boundary, newLine);
sw.Flush();
_webRequest.ContentLength = ms.Length;
Stream s = _webRequest.GetRequestStream();
ms.WriteTo(s);
ms.Flush();
ms.Close();
s.Close();
var _webResponse = RadWebRetry.ReTryGetWebResponse(_webRequest);
StreamReader _streamReader = new StreamReader(RadWebRetry.ReTryGetResponseStream(_webResponse));
string jsonFormattedResponse = _streamReader.ReadToEnd();
logger.Debug("The response from the save operation : " + jsonFormattedResponse);
}
catch (Exception excp)
{
logger.Fatal("Execption:{0}", excp.ToString());
return false;
}
}
When converting the post method to get it works fine.
//method with Get
private bool sendDataToServiceGet((string url,string data)
{
try
{
HttpWebResponse _webResponse = null;
string urlfull = url + "?Data=" + data;
HttpWebRequest _webRequest = (HttpWebRequest)WebRequest.Create(urlfull);
Cookie sessionCookie = new Cookie();
sessionCookie.HttpOnly = true;
sessionCookie.Domain = App.ServerIP;
sessionCookie.Name = "session_id";
sessionCookie.Value = App.SessionId;
_webRequest.CookieContainer = new CookieContainer();
_webRequest.CookieContainer.Add(sessionCookie);
_webRequest.Method = "GET";
_webResponse = RadWebRetry.ReTryGetWebResponse(_webRequest);
System.IO.StreamReader _streamReader = new System.IO.StreamReader(RadWebRetry.ReTryGetResponseStream(_webResponse));
string jsonFormattedResponse = _streamReader.ReadToEnd();
logger.Debug("The response from the save operation : " + jsonFormattedResponse);
}
catch (Exception excp)
{
logger.Fatal("Execption:{0}", excp.ToString());
return false;
}
}
According to me this exception should not be system related, but we are observing it in system to system basis.

How to use eucalyptus REST api in c#

Could anyone help me with this example of REST api “describe eucalyptus instances” in c# without using AWS sdk for .net?
I give you my sample code. This code is running in aws successfully, but in eucalyptus they give a “404 not found” error.
protected void Page_Load(object sender, EventArgs e)
{
EucaListInstance("xyx/services/Eucalyptus");
}
private void ListEucaInstance(string inboundQueueUrl)
{
// Create a request for the URL.
string date = System.DateTime.UtcNow.ToString("s");
string stringToSign = string.Format("DescribeInstances" + date);
string signature = CalculateEucaSignature(stringToSign, true);
StringBuilder sb = new StringBuilder();
sb.Append(inboundQueueUrl);
sb.Append("?Action=DescribeInstances");
sb.Append("&Version=2013-10-15");
sb.AppendFormat("&AWSAccessKeyId={0}", m_EucaAccessKeyID);
sb.AppendFormat("&Expires={0}", date);
sb.AppendFormat("&Signature={0}", signature);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sb.ToString());
HttpWebResponse response = null;
Stream dataStream = null;
StreamReader reader = null;
try
{
request.Credentials = CredentialCache.DefaultCredentials;
response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Cleanup the streams and the response.
if (reader != null)
reader.Close();
if (dataStream != null)
dataStream.Close();
if (response != null)
response.Close();
}
}
private string CalculateEucaSignature(string data, bool urlEncode)
{
ASCIIEncoding ae = new ASCIIEncoding();
HMACSHA1 signature = new HMACSHA1(ae.GetBytes(m_EucaSecretKey));
string retSignature = Convert.ToBase64String(signature.ComputeHash(ae.GetBytes(data.ToCharArray())));
return urlEncode ? HttpUtility.UrlEncode(retSignature) : retSignature;
}
You would get a 404 error if you are sending the request to the wrong URL. I would verify that you are sending to the correct URL, which would typically be along the lines of:
http://eucalyptus.your.domain.here.example.com:8773/services/Eucalyptus
You can find the URL to use in your deployment by looking in your eucarc file for the EC2_URL value, or by running the "euca-describe-services -T eucalyptus" admin command (in versions up to 4.0, for 4.0 onward you would use "-T compute")

httpwebrequest gives timeout until restarted

I am working on a desktop application developed in C# (.NET environment).
This application connects to remote server using HttpWebRequest. If due to any reason my PC is disconnected from the internet and I re-connect it my application always gives request timeout for HttpWebRequest until I restart my whole application and if I again add new thread to my application after network d/c it works fine.
Is there any way to reset my network or anyone can tell me how does it work?
//my code is..
public String request(String add, String post, int time, String reff, int id, int rwtime)
{
try
{
if (rwtime == 0)
{
rwtime = 100000;
}
string result = "";
string location = "";
// Create the web request
HttpWebRequest req = WebRequest.Create(add) as HttpWebRequest;
req.ReadWriteTimeout = rwtime;
req.KeepAlive = true;
req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
req.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
req.ContentType = "application/x-www-form-urlencoded";
req.Timeout = time;
req.Referer = reff;
req.AllowAutoRedirect = false;
req.CookieContainer = statictk.cc[id];
req.PreAuthenticate = true;
if (post != "")
{
req.Method = "POST";
string postData = post;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
// Set the content type of the data being posted.
req.ContentType = "application/x-www-form-urlencoded";
// Set the content length of the string being posted.
req.ContentLength = byte1.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
newStream.Close();
}
else
{
req.Method = "GET";
}
// Get response
try
{
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
// Get the response stream
location = response.GetResponseHeader("Location");
if (location == "")
{
Stream responseStream = response.GetResponseStream();
if (response.ContentEncoding.ToLower().Contains("gzip"))
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
else if (response.ContentEncoding.ToLower().Contains("deflate"))
responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
StreamReader reader = new StreamReader(responseStream, Encoding.Default);
// Read the whole contents and return as a string
result = reader.ReadToEnd();
}
else
{
result = location;
}
response.Close();
if (result == "") result = "retry";
return result;
}
catch (Exception e)
{
log.store("errorinresponce", e.Message);
if (statictd.status[id] != "removed")
{
return "retry";
}
else
{
return "error";
}
}
}
catch(Exception f)
{
log.store("Networkerrorretry", f.Message);
if (f.Message == "The operation has timed out")
{
return "retry";
}
string ans = MessageBox.Show("There was a Network Error..Wish to Retry ?\nError msg : "+ f.Message, "Title", MessageBoxButtons.YesNo).ToString();
if (ans == "Yes")
return "retry";
else
{
Invoketk.settxt(id, "Not Ready");
return "error";
}
}
}
It sounds like your application is missing some error handling. A disconnect can happen at any time and your application should be able to handle it. Try to surround the network loop with a try-catch statement, and then catch for the different kinds of exceptions. Depending on what exception was thrown, you can then decide if you reconnect to the server silently or if you want to generate an error message.

problem in uploading data with HttpWebRequest

Request you to please help me to solve my problem. I am new to web-services and HTTP.
I wrote following code to update data to website. Code run; but I am not able to see my data if uploaded. Here we have facility to see what data is getting uploaded but I am not able to see my data.
// Above URL is not real as I do not want to disclose real URL as of Now
Uri targetUrl = new Uri("http://www.x86map.com/post-embed/ewspost");
HttpWebRequest request = null;
StringBuilder sb = new StringBuilder();
Stream requestStream = null;
try
{
request = (HttpWebRequest)WebRequest.Create(targetUrl);
using (StreamReader inputReader = new StreamReader("C:\\SupportXml.xml"))
{
sb.Append(inputReader.ReadToEnd());
}
String postData = sb.ToString();
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataBytes.Length;
request.KeepAlive = true;
request.Accept = "*/*";
request.Headers.Add("Cache-Control", "no-cache");
request.Headers.Add("Accept-Language", "en-us");
request.Headers.Add("Accept-Encoding", "gzip,deflate");
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8,q=0.66,*;q=0.66");
requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
}
catch (Exception ex)
{
Console.Write(ex.ToString());
}
finally
{
if (null != requestStream)
requestStream.Close();
}
URL I mentioned in Code is not real. Please let me know what is the problem in my code.
Following is the Java code working perfect. I want to convert same code in C#.
// Above URL is not real as I do not want to disclose real URL as of Now
String urlString = "http://www.x86map.com/post-embed/ewspost";
StringBuffer s = new StringBuffer();
try
{
String line = null;
BufferedReader input = new BufferedReader(new FileReader("C:\\SupportXml.xml"));
while ((line = input.readLine()) != null)
{
s.append(line);
s.append(System.getProperty("line.separator"));
}
String xmlDataString = s.toString();
int length = xmlDataString.length();
System.out.println("length " + length);
URL url = new URL(urlString);
System.out.println(url.toString());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setAllowUserInteraction(false);
connection.setUseCaches(false);
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", (String.valueOf(length)));
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Accept-Language", "en-us");
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8,q=0.66, *;q=0.66");
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
BufferedReader reader = new BufferedReader(new StringReader(xmlDataString));
System.out.println("Proxy Used :" + connection.usingProxy());
int dataRead;
bos.write("XML_string=".getBytes());
while ((dataRead = reader.read()) != -1)
{
bos.write(dataRead);
}
bos.flush();
bos.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String res = null;
while ((res = br.readLine()) != null)
{
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
Please help me to resolve this issue.
Thanks and Regards,
map125
You may find it helps to include
requestStream.Flush();
before .Closeing it.
Stream.Flush
I do not see the code that actually gets the response. Is this want is missing?
using (var r = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8))
result = r.ReadToEnd();

Categories