What is a structure of a standard POST request - c#

I am using C# for my project, can anyone tell me what is a standered structure of a HTTP POST Requset. How to attach POST data like a file in the Request from code.
Simply i want to create a POST request from my code itself, with diffrent items to be posted available.
I have checked Ietf's RFC for http POST but its too long....

Specs for simple reference
I have always appreciated HTTP Made Really Easy as a starting point. It's small, concise and friendly.
Often you can get enough implementation details (or at least enough understanding) from this guide's simple style to suffice your need. It has worked for me many times. There is a section on POST. The guide builds cumulatively.
Additionally it links to proper specifications and fuller resources should you need to reference them and get into more detail.
.NET Supporting Classes
Fortunately the .NET Framework Class Library contains higher level classes that can simplify your life. Look into the MSDN documentation and examples about System.Net.WebClient (doesn't lend itself as well to POST, favours GET for quick usage methods). Consider the more flexible System.Web.HttpRequest and System.Web.HttpResponse counterpart classes.
Example using C#
This code sample shows the concept of posting binary data to a stream.
This method is called like:
PostMyData(Stream_instance, "http://url_to_post_to");
Namespaces involved are:
using System.IO;
using System.Net;
The custom method would look something like the following.
Note: Concept taken from MSDN sample code here.
Although I use MIME type application/octet-stream for generic binary data, you can use any well known type from this list of mime types to target the kind of binary data you are sending.
public int PostMyData(Stream binaryData, string postToUrl) {
// make http request
var request = (HttpWebRequest)WebRequest.Create(postToUrl);
request.Method = "POST";
request.ContentType = "application/octet-stream"; // binary data:
// data (bytes) that will be posted in body of request
var streamOut = request.GetRequestStream();
binaryData.CopyTo(streamOut);
// post and get response
using (var response = (HttpWebResponse)request.GetResponse()) {
var code = response.StatusCode;
return (int)code;
}
}

Use HttpWebRequest, its always the best way, but for a more simple aproach on Http Post read:
http://programaticallyspeaking.site40.net/blog/2010/11/how-to-implement-an-http-server-part-1/

Hey i found a way to view a sample POST request, Use Fiddler to track HTTp transfers and click on RAW to view raw data being transfered.

Related

Elasticsearch scroll when using a simple HTTP POST method in a C# console program

I have a C# console program which is retrieving a large amount of data in raw JSON format. This work well using this code:
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
client.Headers["Content-Type"] = "application/json";
client.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
string myDataResult = client.UploadString(url, "POST", myQuery);
<result handling code>
}
At the moment there is no maximum size, but in a short while there will be a limit of 3000. This means I have to use scrolling to get all the data I need. I have been reading about NEST, but I hope to avoid it. I just need the raw JSON output my request i producing. Any simple ways to extend my code so it uses scrolling?
Best regards, Brian
You will need to maintain and pass in to your request what page you're requesting, and the limit (number of items you want returned).
I would take a look at the ElasticSearch API docs for examples of how the request body would look. https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html
Going off of this, it looks like "from" would be the page you're requesting, "size" would be the limit or number of items you want.

How to obtain data from a website and process it in C#

I would like to make a console application that can query a website for data, process it, and then display it. ie- Access http://data.mtgox.com/ and then display the rate for currency X to currency Y.
I am able to get a large string of text via WebClient and StreamReader (though I don't really understand them), and I imagine that I could trim down the string to what I want and then loop the query with a delay to enable updating of the data without running the program again. However I'm only speculating and it seems like there would be a more efficient way of accessing data than this. Am I missing something?
EDIT - The general consensus seems to be to use JSON to do this; which is exactly was I was looking for! Thanks guys!
It looks like that site provides an API serving up JSON data. If you don't know what JSON is you need to look into that, but basically you could create object models representing this JSON. If you have the latest version of VS2012 you can copy the JSON and right click, hit paste special, then paste as class. This will automatically generate models for you. You then contact the API, retrieve the JSON, deserialize it into your models, and do whatever you want from there.
A better way:
string url = "http://data.mtgox.com/";
HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
myWebRequest.Method = "GET"; // This can also be "POST"
HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());
string myPageSource = string.Empty;
myPageSource= myWebSource.ReadToEnd();
myWebResponse.Close();
// Do something with the data in myPageSource
Once you have the data, look at JSON.NET to parse it

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);

How to View HTTPRequest information

I'm designing a web interface that is responsible for communicating with a piece of hardware. The hardware contacts the web page and sends an HTTP Request using POST that contains specific data in the body of http package using a "key=value" format.
Server-side I have code that does the following:
public override void ProcessRequest(HttpContext curContext)
{
if (curContext != null)
{
HttpResponse response = curContext.Response;
response.Clear();
response.ContentType = "text/plain";
response.BufferOutput = true;
response.StatusCode = 200; // HttpStatusCode.OK;
response.Write(response.StatusCode.ToString());
response.End();
}
}
But what I really need is the necessary code to review the Body and retrieve the data (which is in text/plain format). I'm fairly new to this type of web programming so I don't know exactly what code to write to look in the curContext to get this information, or if I even have my override method correct.
I was expecting to have something available like curContext.Request.Body but this isn't the case. How can I see the raw POST data in body of the Request? Can anyone point me in the right direction?
Thanks
You'll want to use the InputStream property on the HttpRequest instance returned by the Request property exposed by the HttpContext passed to your ProcessRequest method.
This will give you the contents of the POST request (which you can verify with a call to the HttpMethod property on the same HttpRequest).
Note that you'll have to use a StreamReader in order to convert the byte stream into strings which you'd then decode (since those key/value pairs should be url-encoded).
Fortunately, this is already done for you. On the HttpRequest instance, you can use the NameValueCollection returned by the Form property to check for the values passed as part of a POST request with url-encoded key/value pairs like so:
public override void ProcessRequest(HttpContext curContext)
{
if (curContext != null) return;
string value = curContext.Form["key"];
// Do other processing.
...
Note that you can also use the indexer on the HttpRequest, but that combines everything exposed by the QueryString, Form, Cookies and ServerVariables collections which I would say in this case is a bad idea, as you are specifically posting information and expecting that on the other side.
If you are putting the data in the body of the request in "key=value" format, it sounds like you are URL encoding form data (as long as you are delimiting the key/value pairs with an ampersand (&).
If that's the case, you should be able to use:
curContext.Request["key"]
And it will give you "value" in your example.

Categories

Resources