Send back an HTTP Response without receiving a Request - c#

I have a C# server that will accept connections from a game/client and return information from a database to the game/client.
The client posts an xml file. I would like to send a 200 OK Response back to the client.
I have tried numerous things. Can anyone suggest something. I also need the response to HTTP 1.0.
Thanks.

If you're looking to write an application that serves web requests with responses and want it to be (relatively) lightweight, at least in regards to IIS, try looking into the Kayak Project. Seems pretty close to what you're aiming to do.
This thread in the mailing list seems especially relevant.

Your question is so confusing... "send back" without request in the title... but a request is done when you explain later the full problem...
Anyway, I don't know if this is what you want to do, but can send your own headers using the Status and StatusCode properties of the HttpResponse class.

So I didn't really understand the http response. I forgot to send back the two CRLF at the end of the response. Thanks alot.
--definitions: CRLF = "\r\n"; s = NetworkStream().
StringBuilder str = new StringBuilder();
str.Append("HTTP/1.0 200 OK\r\n");
str.Append("Date: Tue, 17 Aug 2011 11:40:00 EST\r\n");
str.Append("Server: Apache\r\n");
str.Append("Content-Type: text/xml\r\n");
str.Append("Content Length: 128\r\n");
byte [] r = Encoding.ASCII.GetBytes(str.ToString() + CRLF+ CRLF);
s.Write(r, 0, r.Length);

Related

How to get more details on a BadRequest from HttpResponse

I'm trying to connect to a companies web service, but I'm getting a BadRequest value returned. I suppose that isn't a huge issue, and I'm not asking for help on how to fix the bad request. The issue I'm running into, is how to get more details on what is causing it. So I have this HttpResponseMessage Class variable:
HttpResponseMessage response = c.Post(address, content);
//...fill in content
response = cAssessments.Post(addressInfo, content); //return "Bad Response"
I send it off to their servers with the proper content, and I get back 400 response stating "Bad Request". My question is how do I dig deeper into that repsonse variable to see exactly what is causing it. I'm figuring that there is some dependance on the service I'm hitting to supply information so I'm going to assume it's in there somewhere. But what are something things inside that variable I should be looking into? For example:
"response.StatusCode" gives me the the 400 code. What other properties can I look into?
Any help is appreciated.
Filling content of BadRequest response with some useful tip or information what could possibly go wrong is totally up to web service which serves response. You cant do anything from your side.
Try the Content itself, also the URL of the originating request.
Depending on the API you're requesting against, they may include what specifically caused the 400 in the response's Content.
Also the format you are requesting it in (json vs xml vs whatever)
It all depends on what the service is returning. To check that, you can read the response stream:
using (var stream = response.GetResponseStream ()){
using (var reader = new StreamReader(stream, Encoding.UTF8)
{
var text = reader.ReadToEnd();
// text contains your info
}
}
Another useful option for debugging is using something like postman, where you can paste in your request and see the full response immediately
If the response doesn't include any useful info, you're stuck though, there's nothing you can do about that.

Translating this to a HTTP POST in C#

I am currently experimenting with the HTTP request. I have successfully managed to do get requests and I have read on doing post request with HTTP request.
Now I am trying to work with the yahoo API and in order to use the Yahoo api it states that at
The Message Management API can be used to send a message to another
Yahoo! Messenger contact. The API is very simple to use, as shown
here. Note that the contact that the message is sent to is part of the
URI, using the following format:<server>/v1/message/<network>/<contactID>
POST /v1/message/yahoo/targetYahooId?sid=msgrsessionid
Host: rcore1.messenger.yahooapis.com
Authorization: < Standard OAuth credentials >
Content-Type: application/json;charset=utf-8
Content-Length: 25
{
"message" : "Hey there"
}
Now I have an OAuth string which I obtained from get using the HttpWebRequest object.
The string is something like this
oauth_token=A%3Dvh....aRg--&oauth_token_secret=bd46a....c9239&oauth_expires_in=3600&oauth_session_handle=ALtT.....3J1N4Zg--&oauth_authorization_expires_in=784964948&xoauth_yahoo_guid=TUSKED5...NCIA
UPDATE
Now my question are as follows :
1- If I am using WebRequest object in C# what would my URI look like
2- I understand that it requires a JSON type object. How do i even know what OAuth parameters are ?
One thing you'll need to change is the content type:
request.ContentType = "application/json;charset=utf-8";
And of course, the url.
you need to change the url on the line with the url in it
you need to change the content-type line
you need to make the payload into a json string then convert it to a byte array (byteArray in the sample)
either assemble the json by hand "{ foo:'bar'}" etc or use json.net
and set the content-length
Looks like it's expecting a JSON object for the request body. Depending on the version of .NET you're using, you can either use a Javascript serializer as shown here (https://stackoverflow.com/a/7003815/939080) or JSON.NET (http://james.newtonking.com/projects/json-net.aspx) to convert your form collection into JSON output.
You are asking an open-ended question that would require people to write a bunch of code for you if you want a specific and complete answer. As others have pointed out, there are several issues that you'd need to deal with:
The JSON payload, which would be a straightforward matter of putting the JSON string in the request body via the byteArray used in the code sample.
The content type, which you would need to change as described by jrummell.
The OAuth credentials, which is a kettle of fish you'll need to read about, understand, and acquire a library for. Here's a good place to start looking for a library.

How to use C# .net 4 to get webserver header time

In C# on .net 4.0 I'm trying to get the header date/time of a Internet web site.
My goal is to validate a local systems time (within seconds) of Internet time by using HTTP rather then SNTP. I'm a SNTP fan but it won't do in this scenario. I found this concept of using HTTP headers for time called "HTP" and want to replicate it in C#.
Tried to use HttpWebRequest.Headers collection using MSDN example on the page, which doesn't return me the Date (or much else).
If HttpWebRequest.Headers is a good way to go about getting this value, why can't I see Date in this result? Is there a better way?
var myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
myHttpWebRequest.GetResponse();
Console.WriteLine("\nThe HttpHeaders are \n\n\tName\t\tValue\n{0}",
myHttpWebRequest.Headers);
You seem to be reading the request headers, instead of reading the response headers:
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
var response = myHttpWebRequest.GetResponse();
Console.WriteLine("\nThe HttpHeaders are \n\n\tName\t\tValue\n{0}", response.Headers);

HttpWebRequest type "GET" returning error 400

It seems to be occurring only one machine and none of the other machines.
HttpWebRequest myRequest =(HttpWebRequest)WebRequest.Create("https://connect.zystemsgo.com/auto/");
myRequest.Method = "GET";
SetCertificatePolicy();
Application.DoEvents();
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(),System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
I tried searching other 400 request errors, but it is not clear. How do I go about debugging this?
HTTP Error 400 means Bad Request. This is being returned by the server.
Usually, when I'm debugging HTTP requests, I use Fiddler to monitor the requests and responses and find out what's going on. It never fails.
(Not really an answer, but too big for comment)
For what it's worth, I ran the following Python code (too lazy to spin up C# :), and it worked fine:
import httplib
conn = httplib.HTTPSConnection('connect.zystemsgo.com')
conn.request('GET', '/auto/')
resp = conn.getresponse()
data = resp.read()
print data # expected ouput, just like visiting in a browser
print resp.status # 200
Are you sure you are showing us the URL that is actually failing, or is your code a more general example?
Perhaps the server certificate is not installed on that machine? I wouldn't expect a HTTP 400 in that case, but it's the only thing I can think of so far...
it is a bad request error .Are there no parameters in the request?
Can you post the response message,it will give some idea of what is going wrong.
The code that i supplied in the comment above works.
WebClient webClient = new WebClient();
webClient.DownloadFile("Your complete url for the file", #"c:\myfile.txt");
you need to have permission to write in the directory of your choice.
You could also try and use the async download if you want.I am not getting why it would not work on a certain machine.

vexed! POST returns a 302 found object moved error in HttpWebRequest

Someone please help - been struggling with this lousy problem!
What I'm doing - I have an ASPX page from which I originate a GET and then a POST to a HTTPS page with a view to login to it. I have spent quite a bit of time comparing my GET and POST construction to a browser GET/POST using fiddler (protocol analyzer) and my requests are fine.
However, when I try login through the browser, everything works fine and it logs in. When I run my page, I can see the correct GET and POST, but I get a 302 found 'object moved error'
Originally I thought this was a cookie issue, but after much experimentation I'm pretty sure this has nothing to do with cookies. I have disabled cookies AND javascript on the browser and tried, and the pages work fine without either. I then simulated the exact GET/POST.
This is my situation:
My GET and the browsers GET are EXACTLY THE SAME
The 200 OK response from the site is EXACTLY the same EXCEPT three VIEWSTATE variables which have slightly different lengths (why? why different even if GET is same?)
My POST and the browsers POST are EXACTLY the same EXCEPT the 3 Viewstate variables (I fill it correctly from the GET)
And yet, the browser logs in, while I get a 302 found / object moved errror.
A couple of other things -
a) I copied the POST response from a recent browser POST and replaced my POST params with this browser POST and that got me the right response! This indicates that
- my headers are just fine
- my coding setup / environment etc. are fine
- something fishy in the VIEWSTATE values, which can only be because the browser sent it to me in the first place (there is no corruption in my parsing the GET VIEWSTATE variables and using it in POST, it's perfectly fine)
update I have also tried WebClient just to check - no difference, same 302.
update The object moved basically points to a error page which says 'a serious error occurred blah blah' - the POST is causing a error at the server, and the ONLY difference between the good POST (of the browser) and my POST are the Viewstate variables.
So - WHAT AM I DOING WRONG? Why is this cruel world tormenting me?!!
(PS - one other difference in the browser sequence, not sure how it matters)
Browser:
CONNECT
GET
GET (for a favicon, which returns an error)
CONNECT
POST (success)
Me:
CONNECT
GET
POST (flaming failure, 302 - page moved)
and for those who care, my POST header construction code
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.UserAgent = chromeUserAgent;
//myRequest.CookieContainer = cCookies;
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.Accept = chromeAccept;
myRequest.Referer = url;
myRequest.AllowAutoRedirect = false;
myRequest.Host = "thesitethatskillingme.com";
myRequest.Headers.Add("Origin", "https://thesitethatskillingme.com");
myRequest.Headers.Add("Accept-Encoding", chromeAcceptEncoding);
myRequest.Headers.Add("Accept-Language", chromeAcceptLanguage);
myRequest.Headers.Add("Accept-Charset", chromeAcceptCharset);
myRequest.Headers.Add("Cache-Control", "max-age=0");
myRequest.ServicePoint.Expect100Continue = false;
myRequest.Method = "POST";
myRequest.KeepAlive = true;
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] bData = ascii.GetBytes(data);
myRequest.ContentLength = bData.Length;
using (Stream oStream = myRequest.GetRequestStream())
oStream.Write(bData, 0, bData.Length);
...and then read stream etc. no cookies.
I finally figured it out - and hopefully someone else who chances upon the same problem does not have to go through this again. It's possible that most HTTP gurus and people familiar with WWW development would never hit it, but a newbie quite well could.
So what was the problem? I had narrowed down the problem to VIEWSTATE which I always suspected (see my post above...). It turns out that all I had to do was to Server.UrlEncode the parsed VIEWSTATE values before putting them onto POST - that's it. It took me all day to get to that.
SO, as a learning to other newcomers
If you are trying to POST to a page through code and need to send it VIEWSTATE variables that you parsed from GET, then first Server.UrlEncode it before creating the parameters - for e.g.
do GET
get the response stream into a string
parse the string (I use HtmlAgilityPack- fabulous)
param1 = name +"="+Server.UrlEncode(value)+"&"
POST param = param1+param2+...
-send this in POST - voila, it works
because I have never, ever programmed with HttpWebRequest etc., I started by narrowing down my problem by eliminating cookies, javascript, GET construction, POST construction one-by-one using fiddler (great analyzer tool, free) and then finally did byte-comparison using BeyondCompare, and that's when I caught the VIEWSTATE variable modifications.
I learnt a lesson on URL encoding, and hopefully you won't have to!

Categories

Resources