Currently we have a Windows Service which processes messages from RabbitMQ. It does this by using a web request to a URi. We then read the response and then proceed from there if it is successful.
Process Messages Method
//Deserialze the response
PMResponse res = (PMResponse)ser.ReadObject(GetResponse(addr + paramArgs));
GetResponse Method
private static MemoryStream GetResponse(string URi)
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(URi);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
//Console.WriteLine(responseFromServer);
MemoryStream mStrm = new MemoryStream(Encoding.UTF8.GetBytes(responseFromServer));
reader.Close();
dataStream.Close();
return mStrm;
}
The service is installed on one of our servers where, last week out of nowhere, the application stopped processing messages.
The web service we use to process the SMS messages works fine when we open the parameterised URL in the web browser.
The service also works on my local machine. However when deployed on the server either as a service or as a test console application the operation times out.
What problems do you think there are? The code works, just not on this server.
Answering to save people time:
"The problem is resolved, the company we use for sending the SMS restarted their servers and it worked fine. Many man hours wasted on this before it even got to me hah. Thanks for your time guys."
Related
I have a URL that I want to open in my C# app. This URL is used to talk to a communications device, not an internet web site. I have gotten by (I think) all the cert stuff. But the text I get back in the program IS NOT the same thing that CORRECTLY displays when I use a web browser.
Here's the code.
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Web;
namespace VMLConnStatus
{
class Program
{
static void Main(string[] args)
{
System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();
// Create a request for the URL: https://192.168.30.15/cgi-bin/connstatus?202
String url = "https://192.168.30.15/cgi-bin/";
String data = "connstatus?202";
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = data;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
Console.ReadLine();
}
}
public class MyPolicy : ICertificatePolicy
{
public bool CheckValidationResult(ServicePoint srvPoint,
X509Certificate certificate, WebRequest request,
int certificateProblem)
{
//Return True to force the certificate to be accepted.
return true;
}
}
}
The result, though not perfectly displayed in Chrome, should be:
NA NA NA NA 4c:cc:34:02:6d:26 00:23:A7:24:A3:B6
But the text I get in the console window is:
Ok
<HTML>
<HEAD><TITLE>Index of cgi-bin/</TITLE></HEAD>
<BODY BGCOLOR="#99cc99" TEXT="#000000" LINK="#2020ff" VLINK="#4040cc">
<H4>Index of cgi-bin/</H4>
<PRE>
. 15Jun2014 09:48
0
.. 15Jun2014 09:48
0
connstatus 15Jun2014 09:48
19580
firmwarecfg 15Jun2014 09:48
45736
webcm 15Jun2014 09:48
23836
</PRE>
<HR>
<ADDRESS><A HREF="http://www.acme.com/software/mini_httpd/">mini_httpd/1.19 19de
c2003</A></ADDRESS>
</BODY>
</HTML>
Not EVEN close to the same thing.
What am I doing wrong?
Chuck
UPDATE: Code changed. URL, GET, and request writing (presuming I understood the directions). New code is:
static void Main(string[] args)
{
System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();
// Create a request for the URL: https://192.168.30.15/cgi-bin/connstatus?202
String url = "https://192.168.30.15/cgi-bin/connstatus?202";
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "GET";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Get the request stream.
//Now it throws an exception here--------------------------------
//"Cannot send a content-body with this verb-type."
Stream dataStream = request.GetRequestStream();
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
Console.ReadLine();
}
You are using http method POST but the url you have in the comment looks more like GET so then you probably need WebRequest.Create(url + data).
The incorrect response is the index page for https://192.168.30.15/cgi-bin/ which if you put into Chrome will give you the same "wrong" response.
You might not need to write any data to the request stream and can change the Method and ContentType for the request.
The solution required two parts.
First, doing the proper things, thus a total code rework.
I had the dreaded "The server committed a protocol violation. Section=ResponseHeader Detail=Header name is invalid". I tried to make the programatic solution for this work, but it is a .NET 2.0 solution and I was not able to figure it out in .NET4+. So, I edited the .config file and went on.
Here's the final code:
//Initialization
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(#"https://192.168.30.15/cgi-bin/connstatus?202");
//method is GET.
WebReq.Method = "GET";
//Get the response handle
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//read the response
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
//display it
Console.WriteLine(_Answer.ReadToEnd());
//pause for the ENTER key
Console.ReadLine();
This was added to the .config file in the debug folder (and would be added in the Release folder also..... using VS2013)
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing = "true"/>
</settings>
</system.net>
Thank-you to everyone that replied. The inspiration helped me get to the solution.
I am trying to use an API and I don't have any problems with GET and POST but PUT isn't working. I tried with a lot of different examples and finally by chance I discovered that waiting more that 5 seconds (with 5000ms it is not working and with 5100ms it does) it starts working properly. But why is that happening? And how can I avoid this? 5 seconds for each registry update is to much waiting and I really don't understand why POST works well without waiting and PUT needs 5 seconds to work.
Here I put the method that I am using with the Thread.Sleep(5100). As I said without this line when I make WebResponse response = request.GetResponse(); gives me an error.
public void call(string url, object jsonObj)
{
try
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(urlSplio);
// Create POST data and convert it to a byte array.
request.Method = "PUT";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
request.Credentials = new NetworkCredential(WebConfigurationManager.AppSettings["User"], "WebConfigurationManager.AppSettings["Key"]");
string json = JsonConvert.SerializeObject(jsonObj);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Thread.Sleep(5100);
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
}
}
I think you might want to rewrite the response stream code
Take a look at this walkthrough on MS MS walkthrough
private byte[] GetURLContents(string url)
{
// The downloaded resource ends up in the variable named content.
var content = new MemoryStream();
// Initialize an HttpWebRequest for the current URL.
var webReq = (HttpWebRequest)WebRequest.Create(url);
// Send the request to the Internet resource and wait for
// the response.
// Note: you can't use HttpWebRequest.GetResponse in a Windows Store app.
using (WebResponse response = webReq.GetResponse())
{
// Get the data stream that is associated with the specified URL.
using (Stream responseStream = response.GetResponseStream())
{
// Read the bytes in responseStream and copy them to content.
responseStream.CopyTo(content);
}
}
// Return the result as a byte array.
return content.ToArray();
}
Iam developing a cross platform android app in Xamarin. I want to send a request to register my device. Iam sending my DeviceId, DeviceName and EncodedAccountName i.e my email id.
But I dont get any response. I have tested the request on Postman and get a proper response.
Here is my code:
StringBuilder registerContent = new StringBuilder();
registerContent.Append("DeviceId=").Append(deviceId).Append("&");
registerContent.Append("Name=").Append(deviceName).Append("&");
registerContent.Append("EncodedAccountNameā€¸=").Append(username);
WebRequest request = WebRequest.Create(EndPoints.RegisterDeviceEndPoint);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = registerContent.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType= "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();// Dont get any response here
// Display the status.
System.Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
System.Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return response.ToString();
Any ideas on what might me going wrong?
Thanks
This is how I notify my Web API and wait for a string response:
string myParameters = "?firstParam=" + someParam1 + "&secondParam=" + someParam2;
string url = someHTTPAddress + myParameters;
stringResponseFromWebAPI = (new WebClient()).DownloadString(url);
I'm trying to retrieve the oauth access token to make calls to some google apis in asp.net mvc, and I wrote the following code for an action:
public ActionResult GetOAuthToken()
{
String url = "https://accounts.google.com/o/oauth2/token";
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
request.Host = "accounts.google.com";
// Create POST data and convert it to a byte array.
string postData = String.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", Request.QueryString["code"].ToString(), OAuthConfig.client_id, OAuthConfig.client_secret, OAuthConfig.token_redirect_uri);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteArray = encoding.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// SOME CODE TO PROCESS THE RESPONSE
Response.Redirect("/Home");
return View();
}
OAuthConfig is just a class that contains the client id, client secret etc.
I keep getting 'The remote server returned an error: (400) Bad Request.' at the request.GetResponse() line. Where am I going wrong?
Google does provide a higher level library to work with its services, this handles the formatting of the urls and I find it makes it a lot easier to work with their apis. See http://code.google.com/p/google-api-dotnet-client/
i am trying to post a data to a website and get the response back from the server. This is the code that i am using:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://www.indianrail.gov.in/train_Schedule.html");
((HttpWebRequest)request).UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:9.0) Gecko/20100101 Firefox/9.0";
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = lccp_trnname.Text;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
try
{
WebResponse response = request.GetResponse();
// Display the status.
Response.Write(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Response.Write(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch (WebException ee)
{
Label1.Text = ee.Message;
}
instead of getting the reply back from the server, i am getting redirected to the same webpage in which i am posting the data. Plz help me if anyone has got any idea as what has gone wrong with my code. i've been trying since long back but all efforts went in vain. So plz help
You must post data to http://www.indianrail.gov.in/cgi_bin/inet_trnnum_cgi.cgi instead of http://www.indianrail.gov.in/train_Schedule.html
UPDATE:
The second problem is that you are not sending name of "lccp_trnname" parameter in data. This will make it work:
string postData = "lccp_trnname=" + lccp_trnname.Text;