Make a request to StackExchange Api [duplicate] - c#

This question already has answers here:
.NET: Is it possible to get HttpWebRequest to automatically decompress gzip'd responses?
(3 answers)
Closed 7 years ago.
I'm trying to request list of tags on StackExchange in JSON format by url, but problem is, that I'm getting some broken text instead of JSON, so I can't even parse it.
P.S. Done it with the help of RestSharp.
private void Refresh()
{
var client = new RestClient("http://api.stackexchange.com/2.2/tags?order=desc&sort=popular&site=stackoverflow");
var result = client.Execute(new RestRequest(Method.GET));
var array = JsonConvert.DeserializeObject<Root>(result.Content);
Platforms = array.Platforms;
}

If you make GET request to this URL using Fiddler, you will see that response has a header:
Content-Encoding: gzip
Which means that response is compressed with gzip. Good news is that HttpWebRequest can handle that:
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
After you add this row you will get nice and readable JSON.

As #peeskillet mentions, this looks like compressed data. Please have a look at
What is the canonical method for an HTTP client to instruct an HTTP server to disable gzip responses? and especially this answer.
Something like
Accept-Encoding: *;q=0
should help.

Related

How to post a json and get a file stream in return in Framework 3.5?

I wrote a webservice (web api 2) and tested it successfully with the http Client. One of the Services took a json string and validated it, and then returned an appropriate download stream.
Now though I found out that I Need to write a 3.5 Framework Client for handling the whole Transfer (posting the json data and then getting the file).
As example for getting a text with web Client:
private string GetTextFromUrl(string url, JObject jsonObject)
{
WebClient webClient = new WebClient();
webClient.Headers.Add("content-type", "application/json");
return Encoding.ASCII.GetString(webClient.UploadData(url, Encoding.Default.GetBytes(jsonObject.ToString())));
}
Now though I'm a bit at a loss. From what I see with the webclient only OpenRead and DownloadFile return streams while everything else Returns a Byte Array.
Both though use only the URL and don't do any Posts (like upload data does). So I'm wondering there: Is there any possibility to post json data to a URL and receive a stream in Response with Framework 3.5? (not necessarily limited to webclient).
Edit:
To clarify as it was asked: The Client Posts a json string to the Server and receives a stream in Response. That is what I try to achieve (Client side wise).
I think you have 2 options but that is not really the problem. I think you are missing out on JSON.NET
Using WebClient
Post using webclient in .NET 3.5 is done as below by specifying headers and the "POST" method.
System.Net.WebClient client = new System.Net.WebClient();
client.Headers.Add("content-type", "application/json");//set content-type header here
string response = Encoding.ASCII.GetString(client.UploadData("http://localhost:1111/Service.svc/SignIn", "POST", Encoding.Default.GetBytes("{\"Data\": \"JSON DATA HERE\"}")));
Usually when you do the above, you should get a response from the upload method that you can assign to a variable 'response' and then use JSON.NET.
Please see this link here as well. He doesn't specify the method but uses JSON.NET and seems to work for him.
Using WebRequest
You could also try WebRequest. Please see this link for webrequest example
Hope this helps.

Best way to send HTTP requests in an ASP.NET webforms project c# [duplicate]

This question already has answers here:
How to simulate HTTP POST programmatically in ASP.NET?
(5 answers)
Closed 5 years ago.
Hey guys im a newbie working with HTTP requests in C#/.Net and would love some tips and suggestions of the correct namespaces or classes that would make doing HTTP requests easier. GET,POST,.etc
Ive come across a few such as the HTTPrequest class, and also the HTTP.WebRequest but im lost as to which to actually use and any advice would be welcome!
The short answer is that you have to make use of HttpWebRequest to make the request and HttpWebResponse to get the response. But this will probably not solve your problem as the configurations for making HTTP requests differ from one case to another. For example, headers, content type, and accept are parameters to which you have to pay attention based on your method (GET, POST,PUT,PATCH,DELETE) and the API with which you are communicating.
For example, let's say that you wanna send and receive a text message, you should follow something like this:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("URL");
webRequest.ContentType = "text/plain;charset=UTF-8";
webRequest.Accept = "text/plain;charset=UTF-8";
webRequest.Method = "POST";
using (StreamWriter requestStream = new StreamWriter(webRequest.GetRequestStream())) {
requestStream.WriteLine("Hello");
}
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(webResponse.GetResponseStream())) {
Console.WriteLine(responseStream.ReadToEnd());
}
You have to keep in mind that your request type (ContentType) or your response type (Accept) may be in different formats such as XML or JSON or even Stream and you have to find the correct settings for your case. You may also need to add custom HTML headers in your request.

Sending a POST request to a URL from C# [duplicate]

This question already has answers here:
Send HTTP POST request in .NET
(16 answers)
Closed 5 years ago.
I have a Node server hosted with Azure, where I can send a POST request to the API for it to perform some function. The API itself works, I have tested it with Post Man.
A call to the API would look something like this..
http://website.com/api/Foo?name=bar&second=example
This doesn't necessarily need to return anything, as the call is silent and does something in the background. (note: perhaps it must return something and this is a hole in my understanding of the concept?)
Using C#, how can I make a web request to this URL?
I am already constructing the URL based on parameters passed to my method (so name and type as above could be whatever was passed to the method)
It's the POSTing to this URL that I cannot get working correctly.
This is the code I have tried..
void MakeCall(string name, string second)
{
string url = "http://website.com/api/Foo?name="+name+"&second="+second;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = url.Length;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
You have to create a request stream and write to it, this link here has several ways to do this either with HttpWebRequest, HttpClient or using 3rd party libraries:
Posting data using C#

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

Get only response headers [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
HttpWebResponse: closing the stream
Using ASP.NET is it possible to make a request and get only response headers? I have to do a request to a big file, but I only need the response headers, i dont care about the content of the file.
I would like to know if there is something similar to get_headers from php (http://php.net/manual/en/function.get-headers.php).
I'm not sure how to do this natively, but at a minimum, you could use a custom HTTP handler (ASHX) file to create the headers you need, and return nothing else in the response.
Update:
If you set WebRequest.Method = "HEAD" then the server should automatically only return the Headers. This is according to W3.

Categories

Resources