I have been trying to do some http requests in C#. First time doing http request GET it worked, but the second time it didn't work and it returned null, can someone please help?
private static dynamic WebRequestGET(Uri url)
{
try
{
var request = WebRequest.Create(url);
request.Method = "GET";
request.Timeout = 10000;
WebResponse webResponse = request.GetResponse();
var webStream = webResponse.GetResponseStream();
var reader = new StreamReader(webStream);
var data = reader.ReadToEnd();
dynamic jsonData = JObject.Parse(data);
request.Abort();
webResponse.Close();
webStream.Close();
return jsonData;
}
catch(Exception e)
{
var window = GetConsoleWindow();
ShowWindow(window, 1);
Console.WriteLine($"Error occured while fetching data, if error will occur again please create issue on github{Environment.NewLine}{e.Message}");
Console.ReadKey();
Application.Exit();
return null;
}
}
Try using this to make the get request. You might need to add restsharp using nuget.
using RestSharp;
// ^^ put at top of file
var client = new RestClient("https://www.google.com");
var request = new RestRequest();
request.Method = Method.Get;
RestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
// change this to whatever you want ^^
I'd also recommend postman.com since it can generate the code for you.
Related
I'm trying to send a message to a slack channel in C#. with http request, using Webhook url.
In the get response line' I'm getting 400- bad request.
My function:
public void SendSlackAlert(string message, string slackUrl)
{
try
{
var content = $"{{\r\n\"text\":\"{Context}\r\n{message} \"\r\n}}";
if (string.IsNullOrWhiteSpace(slackUrl))
{
return;
}
var httpRequest = WebRequest.Create(slackUrl) as HttpWebRequest;
httpRequest.Method = "POST";
httpRequest.Accept = "application/json";
httpRequest.Timeout = Convert.ToInt32(TimeSpan.FromDays(1).TotalMilliseconds);
var bytesToSend = Encoding.UTF8.GetBytes(content);
httpRequest.ContentType = "application/json;charset=utf-8";
httpRequest.ContentLength = bytesToSend.Length;
using (var requestStream = httpRequest.GetRequestStream())
requestStream.Write(bytesToSend, 0, bytesToSend.Length);
var httpResponse = httpRequest.GetResponse() as HttpWebResponse;
using (var responseReader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
responseReader.ReadToEnd();
}
}
catch (Exception ex)
{
// return "Error";
}
}
I am transferred to catch with the error, in this line:
var httpResponse = httpRequest.GetResponse() as HttpWebResponse;
would greatly appreciate any attempt to help.
Thank you!
I saw elsewhere that having the encoding set can cause issues with the Slack API.
Instead of setting the Content-Type header along with an encoding, try only setting the Content-Type header to application JSON.
Replace this line:
httpRequest.ContentType = "application/json;charset=utf-8";
With this line:
httpRequest.Headers.Add(HttpRequestHeader.ContentType, "application/json");
I have some problems with code. I'm using HttpWebRequest class to do operations
Code as bellow:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072 | (SecurityProtocolType)768;
ServicePointManager.Expect100Continue = true;
//ServicePointManager.DefaultConnectionLimit = 5;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverName + authorizePath);
request.Abort();
byte[] bearerMatch = UTF8Encoding.UTF8.GetBytes("username:password");
//request.Proxy = null; //<TNI_20180808
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/json";
request.Timeout = 100;
//request.Headers["Authorization"] = "Bearer " + Convert.ToBase64String(bearerMatch);
string content = String.Format(authorizeBody, login, password);
content = "{" + content + "}";
try
{
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(content);
}
using (WebResponse response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var responseContent = reader.ReadToEnd();
token = responseContent.Replace('"', ' ').Trim();
}
//response.Close();
//request.Abort();
}
}
catch (Exception ex)
{
throw ex;
}
Until third operation everything is okey, unfortunately i don't know what to do. When application is trying to create request third time there is an timeout error:
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
I think that there is an opportunity to solve this with closing request and response in a proper way but i don't know how to do this. After increasing ServicePointManager.DefaultConnectionLimit operations were getting completed correctly.
Can you help me please? How should i abort or close request/response in a good way?
Thank you!
https://api.github.com/users/[UserName] can be accessed via browser. I get a Json result. But I want to retrieve the same information programmatically.
I'm using the below code, which is not working as expected. Please advice.
var credentials =
string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:",
githubToken);
credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Basic", credentials);
var contents =
client.GetStreamAsync("https://api.github.com/users/[userName]").Result;
As a result of the above code, I'm getting "Aggregate Exception".
How to achieve the requirement using c# code??? Please help
Note: Not expecting a solution with Octokit. Need proper c# code.
I found the solution. Here is the code.
HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.UserAgent = "Anything";
webRequest.ServicePoint.Expect100Continue = false;
try
{
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
string reader = responseReader.ReadToEnd();
var jsonobj = JsonConvert.DeserializeObject(reader)
}
}
catch
{
return;
}
}
Everything was working fine until a couple days ago, I started getting an Unauthorized error when trying to get a Nest Access Token. I've double checked and the client ID and client secret code are all correct. Any ideas on what could be causing it?
HttpWebRequest request = WebRequest.CreateHttp("https://api.home.nest.com/oauth2/access_token?");
var token = await request.GetValueFromRequest<NestToken>(string.Format(
"client_id={0}&code={1}&client_secret={2}&grant_type=authorization_code",
CLIENTID,
code.Value,
CLIENTSECRET));
public async static Task<T> GetValueFromRequest<T>(this HttpWebRequest request, string postData = null)
{
T returnValue = default(T);
if (!string.IsNullOrEmpty(postData))
{
byte[] requestBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (var postStream = await request.GetRequestStreamAsync())
{
await postStream.WriteAsync(requestBytes, 0, requestBytes.Length);
}
}
else
{
request.Method = "GET";
}
var response = await request.GetResponseAsync();
if (response != null)
{
using (var receiveStream = response.GetResponseStream())
{
using (var reader = new StreamReader(receiveStream))
{
var json = await reader.ReadToEndAsync();
var serializer = new DataContractJsonSerializer(typeof(T));
using (var tempStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return (T)serializer.ReadObject(tempStream);
}
}
}
}
return returnValue;
}
While I can't provide an answer I can confirm the same thing is happening to my iOS app in the same timeframe.
Taking my url and post values works fine using postman in chrome. Alamofire is throwing up error 401, as is native swift test code like yours.
Have Nest perhaps changed their https negotiation?
This turned out to be because of a fault on Nest's end which was later fixed.
I am writing a Windows Phone 8 app that is supposed to send an GET+POST request to a server and parse the answer.
The code I am using to send the request and to get a response back is the following (it is written in a separate static class):
// server to POST to
string url = "http://myserver.com/?page=hello¶m2=val2";
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
// Create the post data
string postData = "pseudo=pseudo&titre=test&texte=\"Contenu du message\"";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Write the bytes to the stream
await stream.WriteAsync(byteArray, 0, byteArray.Length);
stream.Close();
IAsyncResult ar = httpWebRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), httpWebRequest);
}
}
private static void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
//For debug: show results
System.Diagnostics.Debug.WriteLine(result);
}
My problem is : I have no idea how to get this answer (the string result) back in my behind-code in my app (or any other method in my app to be honest).
How could I do that?
You can try the following code,
string url = "http://myserver.com/?page=hello¶m2=val2";
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
using (var postStream = webRequest.EndGetRequestStream(asynchronousResult))
{
//send yoour data here
}
webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest);
}
void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest myrequest = (HttpWebRequest)asynchronousResult.AsyncState;
using (HttpWebResponse response = (HttpWebResponse)myrequest.EndGetResponse(asynchronousResult))
{
System.IO.Stream responseStream = response.GetResponseStream();
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
}
}
catch (Exception e)
{
//Handle Exception
}
else
throw;
}
}
public static string GetPageAsString(Uri address)
{
string result = "";
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream(), Constants.EncodingType);
// Read the whole contents and return as a string
result = reader.ReadToEnd();
}
return result;
}
Does it have to be a static class? Because if you have a new webrequest object for each request, then each response will come back into it's own object.v
You need to put the result somewhere that you can access it from the place you want to use it.
e.g. if you put it into another public static variable member then you can read it off where you need to. But you probably need to signal the UI to action it, or bind it to the UI.
If you use a static place to store it, then you will only have one active at a time. Unless you add it to a static list of items or results that you are working with
See also: http://blogs.msdn.com/b/devfish/archive/2011/04/07/httpwebrequest-fundamentals-windows-phone-services-consumption-part-2.aspx
You can: make a global variable in App.xaml.cs:
public string result;
In code use it as
(App.Current as App).result = httpWebStreamReader.ReadToEnd();
If you will need to get notified in your current active page when the result is updated - use delegates after you get the response which will signal to your page.