I want to make a get request. Here is the code I tested:
public string Get(string uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip
| DecompressionMethods.Deflate;
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
but the problem is it will freeze GUI and I found this code:
public async Task<string> GetAsync(string uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip
| DecompressionMethods.Deflate;
using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return await reader.ReadToEndAsync();
}
}
but I am not good at multitasking.
anyhelp how to use this function?
tnx
You are almost there. All you need to do is to call GetAsync function with await and you will get the desired result.
Please do not forget to include async in the signature of calling function. Support you have GetText from where you want to use GetAsync then code snippet would be:
private async void GetText()
{
string str = await GetAsync(url);
}
I don't know what do you want to do, but you can try to remove the usings because you only need to add the usings in the imports section and try to use your method more like this:
public class HttpHandler
{
static HttpClient client = new HttpClient();
public async Task<string> Get(string apiURL)
{
HttpResponseMessage response = await client.GetAsync(apiURL);
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
return await reader.ReadToEndAsync();
}
}
Related
Because of Net 6.0 usage I'm frustrated how to convert old HttpWebResponse to httpClient
Could someone help me to handle it right?
I have httpClient request
var handler = new HttpClientHandler();
if (handler.SupportsAutomaticDecompression)
{
handler.AutomaticDecompression = DecompressionMethods.GZip |
DecompressionMethods.Deflate;
}
var httpClient = new HttpClient(handler);
httpClient.SendAsync(new HttpRequestMessage(new HttpMethod.Post, url));
And I have old HttpWebResponse
using (var dataStream = httpWebRequest.GetRequestStream())
{
var reqDataByte = Encoding.GetEncoding(encoding).GetBytes(reqData);
dataStream.Write(reqDataByte, 0, reqDataByte.Length);
}
using (var httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse())
{
var responseStream = httpWebResponse.GetResponseStream();
if (responseStream != null)
using (var streamReader =
new StreamReader(responseStream, Encoding.GetEncoding(encoding)))
{
getString = streamReader.ReadToEnd();
}
}
Couldn't understand how to handle respond with httpClient right
using var dataStream = httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
var reqDataByte = Encoding.GetEncoding(encoding).GetBytes(reqData);
dataStream.CopyToAsync(reqDataByte, 0, reqDataByte.Length);
using var response = (HttpWebResponse) httpClient.GetResponse();
var responseStream = response.GetResponseStream();
using var streamReader =
new StreamReader(responseStream, Encoding.GetEncoding(encoding));
getString = streamReader.ReadToEnd();
If you are trying to simply post raw bytes and get a string response back it is quite simple. You will need this to be an async method and await the async calls.
var reqDataByte = Encoding.GetEncoding(encoding).GetBytes(reqData);
var response = await httpClient.PostAsync(url, new ByteArrayContent(reqDataByte));
if (response.IsSuccessStatusCode)
{
getString = await response.Content.ReadAsStringAsync();
}
else
{
//Handle any unsuccessful post
}
I am trying to make a program that requests my website with a username, password, hardware ID and a key in POST.
I have this code here that should send a POST request to my website with that form data, but when it sends, my webserver reports back that it didn't receive the POST data
try
{
string poststring = String.Format("username={0}&password={1}&key={2}&hwid={3}", Username, Password, "272453745345934756392485764589", GetHardwareID());
HttpWebRequest httpRequest =
(HttpWebRequest)WebRequest.Create("mywebsite");
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
byte[] bytedata = Encoding.UTF8.GetBytes(poststring);
httpRequest.ContentLength = bytedata.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
HttpWebResponse httpWebResponse =
(HttpWebResponse)httpRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StringBuilder sb = new StringBuilder();
using (StreamReader reader =
new StreamReader(responseStream, System.Text.Encoding.UTF8))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.Append(line);
}
}
return sb.ToString();
}
catch (Exception Error)
{
return Error.ToString();
}
If someone could help me, I would really appreciate it.
As per HttpWebRequest documentation
We don't recommend that you use HttpWebRequest for new development. Instead, use the System.Net.Http.HttpClient class.
HttpClient contains only asynchronous API because Web requests needs awaiting. That's not good to freeze entire Application while it's pending response.
Thus, here's some async function to make POST request with HttpClient and send there some data.
First of all, create HttpClient seperately because
HttpClient is intended to be instantiated once per application, rather than per-use.
private static readonly HttpClient client = new HttpClient();
Then implement the method.
private async Task<string> PostHTTPRequestAsync(string url, Dictionary<string, string> data)
{
using (HttpContent formContent = new FormUrlEncodedContent(data))
{
using (HttpResponseMessage response = await client.PostAsync(url, formContent).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
}
Or C# 8.0
private async Task<string> PostHTTPRequestAsync(string url, Dictionary<string, string> data)
{
using HttpContent formContent = new FormUrlEncodedContent(data);
using HttpResponseMessage response = await client.PostAsync(url, formContent).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
Looks easier than your code, right?
Caller async method will look like
private async Task MyMethodAsync()
{
Dictionary<string, string> postData = new Dictionary<string, string>();
postData.Add("message", "Hello World!");
try
{
string result = await PostHTTPRequestAsync("http://example.org", postData);
Console.WriteLine(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
If you're not familiar with async/await, it's time to say Hello.
I am using asp.net core. I am able to get the response from the http webrequest using GET method. To get the response via http webrequest using POST am facing 405 error.(Remote server not found)
Here is my code using GET Method.
public static void Main(string[] args)
{
var task = MakeAsyncRequest("http://localhost:8080/nifi-api/flow/status", "text/html");
Console.ReadLine();
}
public static Task<string> MakeAsyncRequest(string url, string contentType)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = contentType;
request.Method = "GET";
request.Proxy = null;
Task<WebResponse> task = Task.Factory.FromAsync(
request.BeginGetResponse,
asyncResult => request.EndGetResponse(asyncResult),
(object)null);
return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
}
private static string ReadStreamFromResponse(WebResponse response)
{
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
string results = reader.ReadToEnd();
if (!string.IsNullOrEmpty(results))
{
Data data = new Data();
data = JsonConvert.DeserializeObject<Data>(results);
}
return results;
}
}
Please let me know how to get the response using async POST method in asp.net core. Thanks in advance.
Maybe this way?
HttpClient httpClient = new HttpClient();
var response = await httpClient.PostAsync("http://localhost:8080/nifi-api/flow/status", new StringContent("Json string", Encoding.UTF8, "application/json"));
i am still new on c# and i'm trying to create an application for this page that will tell me when i get a notification (answered, commented, etc..). But for now i'm just trying to make a simple call to the api which will get the user's data.
i'm using Visual studio express 2012 to build the C# application, where (for now) you enter your user id, so the application will make the request with the user id and show the stats of this user id.
here is the code where i'm trying to make the request:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Request library
using System.Net;
using System.IO;
namespace TestApplication
{
class Connect
{
public string id;
public string type;
protected string api = "https://api.stackexchange.com/2.2/";
protected string options = "?order=desc&sort=name&site=stackoverflow";
public string request()
{
string totalUrl = this.join(id);
return this.HttpGet(totalUrl);
}
protected string join(string s)
{
return api + type + "/" + s + options;
}
protected string get(string url)
{
try
{
string rt;
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
rt = reader.ReadToEnd();
Console.WriteLine(rt);
reader.Close();
response.Close();
return rt;
}
catch(Exception ex)
{
return "Error: " + ex.Message;
}
}
public string HttpGet(string URI)
{
WebClient client = new WebClient();
// Add a user agent header in case the
// requested URI contains a query.
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
Stream data = client.OpenRead(URI);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
data.Close();
reader.Close();
return s;
}
}
}
the class is an object and its being accessed from the form by just parsing it the user id and make the request.
i have tried many of the examples i have looked on google, but not clue why i am getting on all ways this message "�".
i am new in this kind of algorithm, if anyone can share a book or tutorial that shows how to do this kind of stuff (explaining each step), i would appreciate it
If using .NET 6 or higher, please read the warning at the bottom of this answer.
Servers sometimes compress their responses to save on bandwidth, when this happens, you need to decompress the response before attempting to read it. Fortunately, the .NET framework can do this automatically, however, we have to turn the setting on.
Here's an example of how you could achieve that.
string html = string.Empty;
string url = #"https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
Console.WriteLine(html);
GET
public string Get(string uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
GET async
public async Task<string> GetAsync(string uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return await reader.ReadToEndAsync();
}
}
POST
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC
public string Post(string uri, string data, string contentType, string method = "POST")
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
request.Method = method;
using(Stream requestBody = request.GetRequestStream())
{
requestBody.Write(dataBytes, 0, dataBytes.Length);
}
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
POST async
Contains the parameter method in the event you wish to use other HTTP methods such as PUT, DELETE, ETC
public async Task<string> PostAsync(string uri, string data, string contentType, string method = "POST")
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.ContentLength = dataBytes.Length;
request.ContentType = contentType;
request.Method = method;
using(Stream requestBody = request.GetRequestStream())
{
await requestBody.WriteAsync(dataBytes, 0, dataBytes.Length);
}
using(HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
using(Stream stream = response.GetResponseStream())
using(StreamReader reader = new StreamReader(stream))
{
return await reader.ReadToEndAsync();
}
}
Warning notice: The methods of making a HTTP request outlined within this answer uses the HttpWebRequest class which is deprecated starting from .NET 6 and onwards. It's recommended to use HttpClient instead which this answer by DIG covers for environments that depends on .NET 6+.
Ref: https://learn.microsoft.com/en-us/dotnet/core/compatibility/networking/6.0/webrequest-deprecated
Another way is using 'HttpClient' like this:
using System;
using System.Net;
using System.Net.Http;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Making API Call...");
using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
{
client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
response.EnsureSuccessStatusCode();
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine("Result: " + result);
}
Console.ReadLine();
}
}
}
Check HttpClient vs HttpWebRequest from stackoverflow and this from other.
Update June 22, 2020:
It's not recommended to use httpclient in a 'using' block as it might cause port exhaustion.
private static HttpClient client = null;
ContructorMethod()
{
if(client == null)
{
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
client = new HttpClient(handler);
}
client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
response.EnsureSuccessStatusCode();
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine("Result: " + result);
}
If using .Net Core 2.1+, consider using IHttpClientFactory and injecting like this in your startup code.
var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
TimeSpan.FromSeconds(60));
services.AddHttpClient<XApiClient>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
}).AddPolicyHandler(request => timeout);
Simpliest way for my opinion
var web = new WebClient();
var url = $"{hostname}/LoadDataSync?systemID={systemId}";
var responseString = web.DownloadString(url);
OR
var bytes = web.DownloadData(url);
var request = (HttpWebRequest)WebRequest.Create("sendrequesturl");
var response = (HttpWebResponse)request.GetResponse();
string responseString;
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
responseString = reader.ReadToEnd();
}
}
Adding to the responses already given, this is a complete example hitting JSON PlaceHolder site.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Publish
{
class Program
{
static async Task Main(string[] args)
{
// Get Reqeust
HttpClient req = new HttpClient();
var content = await req.GetAsync("https://jsonplaceholder.typicode.com/users");
Console.WriteLine(await content.Content.ReadAsStringAsync());
// Post Request
Post p = new Post("Some title", "Some body", "1");
HttpContent payload = new StringContent(JsonConvert.SerializeObject(p));
content = await req.PostAsync("https://jsonplaceholder.typicode.com/posts", payload);
Console.WriteLine("--------------------------");
Console.WriteLine(content.StatusCode);
Console.WriteLine(await content.Content.ReadAsStringAsync());
}
}
public struct Post {
public string Title {get; set;}
public string Body {get;set;}
public string UserID {get; set;}
public Post(string Title, string Body, string UserID){
this.Title = Title;
this.Body = Body;
this.UserID = UserID;
}
}
}
i'm very new to C#, let alone Windows Phone development :)
I'm trying to send a request, get the JSON response, but if there is an error (such as 401), be able to tell the user such. Here is my code:
async Task<string> AccessTheWebAsync()
{
//builds the credentials for the web request
var credentials = new NetworkCredential(globalvars.username, globalvars.password);
var handler = new HttpClientHandler { Credentials = credentials };
//calls the web request, stores and returns JSON content
HttpClient client = new HttpClient(handler);
Task<string> getStringTask = client.GetStringAsync("https://www.bla.com/content");
String urlContents = await getStringTask;
return urlContents;
}
I know it must be something I'm doing wrong in the way that I send the request and store the response...but i'm just not sure what.
If there is an error, I get a general:
net_http_message_not_success_statuscode
Thank you!
You could use te GetAsync() method instead of the GetStringAsync().
HttpResponseMessage response = await client.GetAsync("https://www.bla.com/content");
if(!response.IsSuccessStatusCode)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
do something...
}
}
String urlContents = await response.Content.ReadAsStringAsync();
This way you can make use of the HttpStatusCode enumerable to check the returned status code.
Instead of using an HttpClient use a plain good old HttpWebRequest :)
async Task<string> AccessTheWebAsync()
{
HttpWebRequest req = WebRequest.CreateHttp("http://example.com/nodocument.html");
req.Method = "GET";
req.Timeout = 10000;
req.KeepAlive = true;
string content = null;
HttpStatusCode code = HttpStatusCode.OK;
try
{
using (HttpWebResponse response = (HttpWebResponse)await req.GetResponseAsync())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
content = await sr.ReadToEndAsync();
code = response.StatusCode;
}
}
catch (WebException ex)
{
using (HttpWebResponse response = (HttpWebResponse)ex.Response)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
content = sr.ReadToEnd();
code = response.StatusCode;
}
}
//Here you have now content and code.
return content;
}