calling google Url Shortner API in C# - c#

I want to call the google url shortner API from my C# Console Application, the request I try to implement is:
POST https://www.googleapis.com/urlshortener/v1/url
Content-Type: application/json
{"longUrl": "http://www.google.com/"}
When I try to use this code:
using System.Net;
using System.Net.Http;
using System.IO;
and the main method is:
static void Main(string[] args)
{
string s = "http://www.google.com/";
var client = new HttpClient();
// Create the HttpContent for the form to be posted.
var requestContent = new FormUrlEncodedContent(new[] {new KeyValuePair<string, string>("longUrl", s),});
// Get the response.
HttpResponseMessage response = client.Post("https://www.googleapis.com/urlshortener/v1/url",requestContent);
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(responseContent.ContentReadStream))
{
// Write the output.
s = reader.ReadToEnd();
Console.WriteLine(s);
}
Console.Read();
}
I get the error code 400: This API does not support parsing form-encoded input.
I don't know how to fix this.

you can check the code below (made use of System.Net).
You should notice that the contenttype must be specfied, and must be "application/json"; and also the string to be send must be in json format.
using System;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"longUrl\":\"http://www.google.com/\"}";
Console.WriteLine(json);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
}
}
}

Google has a NuGet package for using the Urlshortener API. Details can be found here.
Based on this example you would implement it as such:
using System;
using System.Net;
using System.Net.Http;
using Google.Apis.Services;
using Google.Apis.Urlshortener.v1;
using Google.Apis.Urlshortener.v1.Data;
using Google.Apis.Http;
namespace ConsoleTestBed
{
class Program
{
private const string ApiKey = "YourAPIKey";
static void Main(string[] args)
{
var initializer = new BaseClientService.Initializer
{
ApiKey = ApiKey,
//HttpClientFactory = new ProxySupportedHttpClientFactory()
};
var service = new UrlshortenerService(initializer);
var longUrl = "http://wwww.google.com/";
var response = service.Url.Insert(new Url { LongUrl = longUrl }).Execute();
Console.WriteLine($"Short URL: {response.Id}");
Console.ReadKey();
}
}
}
If you are behind a firewall you may need to use a proxy. Below is an implementation of the ProxySupportedHttpClientFactory, which is commented out in the sample above. Credit for this goes to this blog post.
class ProxySupportedHttpClientFactory : HttpClientFactory
{
private static readonly Uri ProxyAddress
= new UriBuilder("http", "YourProxyIP", 80).Uri;
private static readonly NetworkCredential ProxyCredentials
= new NetworkCredential("user", "password", "domain");
protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args)
{
return new WebRequestHandler
{
UseProxy = true,
UseCookies = false,
Proxy = new WebProxy(ProxyAddress, false, null, ProxyCredentials)
};
}
}

How about changing
var requestContent = new FormUrlEncodedContent(new[]
{new KeyValuePair<string, string>("longUrl", s),});
to
var requestContent = new StringContent("{\"longUrl\": \" + s + \"}");

Following is my working code. May be its helpful for you.
private const string key = "xxxxxInsertGoogleAPIKeyHerexxxxxxxxxx";
public string urlShorter(string url)
{
string finalURL = "";
string post = "{\"longUrl\": \"" + url + "\"}";
string shortUrl = url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + key);
try
{
request.ServicePoint.Expect100Continue = false;
request.Method = "POST";
request.ContentLength = post.Length;
request.ContentType = "application/json";
request.Headers.Add("Cache-Control", "no-cache");
using (Stream requestStream = request.GetRequestStream())
{
byte[] postBuffer = Encoding.ASCII.GetBytes(post);
requestStream.Write(postBuffer, 0, postBuffer.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader responseReader = new StreamReader(responseStream))
{
string json = responseReader.ReadToEnd();
finalURL = Regex.Match(json, #"""id"": ?""(?.+)""").Groups["id"].Value;
}
}
}
}
catch (Exception ex)
{
// if Google's URL Shortener is down...
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
}
return finalURL;
}

Related

Google FCM gives me BadRequest when I use .NET Core HttpClient

I am trying to use FCM API for sending push notifications on a android application. It works nice if I use some HTTP client like Insomnia or Postman. Is the screen below:
and headers:
Of course, I have a registration ID and FCM Server key instead of xxx.
But I need to send the same from my C# code. And I always have BadRequest. I don't understand why.
Here is my code:
var json = JsonConvert.SerializeObject(new
{
to = customer.FcmRegistrationId,
notification = new
{
body = push.PushBody,
title = push.PushTitle,
sound = "default"
}
});
var content = new StringContent(json, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage
{
RequestUri = new Uri("https://fcm.googleapis.com/fcm/send"),
Content = content,
};
request.Headers.TryAddWithoutValidation("Authorization",
"key=" + customer.FCMServerKey);
HttpResponseMessage response;
using (var client = new HttpClient())
{
response = await client.SendAsync(request);
}
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
And as I've sad before I always have this answer:
Please help me!
I have testet an approach to send push notifications: uses WebRequest.Create
Please set devId (reg-id from your at the fcm registerd device), SERVER_API_KEY und SENDER_ID from your fcm-account.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace SendMsgByFCM
{
public partial class Form1 : Form
{
AndroidGCMPushNotification fcmPush = new AndroidGCMPushNotification();
public Form1()
{
InitForm();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
**devId** = "faxgYiWv4Sk:APA91bGehlGNNGaE20djfaJ5xzQst_b190GvrEwm_yvPsZvY-.....";
fcmPush.SendNotification(devId, 'message ...' );
MessageBox.Show( "msg send" );
}
}
public class AndroidGCMPushNotification
{
public string SendNotification(string deviceId, string message)
{
string **SERVER_API_KEY** = "AAAADtSR7s8:APA91bHhhsjRMeL2gH6Qzv5BbdJyshOtgJ-J....";
var **SENDER_ID** = "636988888888";
var value = message;
WebRequest tRequest;
tRequest = **WebRequest.Create**("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
}
}
I have solved it with the help of the following code:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"key={ServerKey}");
var obj = new
{
to = Id,
notification = new
{
title = Title,
body = Message
}
};
//serialize object data to json
string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
// create an http string content
var data = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://fcm.googleapis.com/fcm/send", data);
return response.StatusCode;
...
Full source is here https://github.com/frankodoom/Firebase.Notification/blob/master/Firebase.Network.Standard/Firebase.cs
I dont know why but data and text in the original source dont work. Use title and body.

how to connect api django 1.10 with c#

I'm trying to connect Django API with c # but when I connect I face a problem in C#.
Django here I use as a server API and C# as a client.
Errors in C# are "CSRF is missing or incorrect".
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Net.Http;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
private static string json;
public static string url { get; private set; }
static void Main(string[] args)
{
/*
try
{
CookieContainer container = new CookieContainer();
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("http://127.0.0.1/api/");
request1.Proxy = null;
request1.CookieContainer = container;
using (HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse())
{
foreach (Cookie cookie1 in response1.Cookies)
{
//Console.WriteLine(response.IsSuccessStatusCode);
var csrf = cookie1.Value;
Console.WriteLine(csrf);
Console.WriteLine("name=" + cookie1.Name);
Console.WriteLine();
Console.Write((int)response1.StatusCode);
//PostRespone("http://localhost/api/multiplyfunction/");
}
}
}
catch (WebException e)
{
Console.WriteLine(e.Status);
}
/* HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/api/");
request.CookieContainer = Cookie; // use the global cookie variable
string postData = "100";
byte[] data = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
WebResponse response = (HttpWebResponse)request.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();*/
WebClient csrfmiddlewaretoken = new WebClient();
CookieContainer cookieJar = new CookieContainer();
var request1 = (HttpWebRequest)HttpWebRequest.Create("http://localhost/api/");
request1.CookieContainer = cookieJar;
var response1 = request1.GetResponse();
string baseSiteString = csrfmiddlewaretoken.DownloadString("http://localhost/api/");
// string csrfToken = Regex.Match(baseSiteString, "<meta name=\"csrf-token\" content=\"(.*?)\" />").Groups[1].Value;
// wc.Headers.Add("X-CSRF-Token", csrfToken);
csrfmiddlewaretoken.Headers.Add("X-Requested-With", "XMLHttpRequest");
using (HttpWebResponse response2 = (HttpWebResponse)request1.GetResponse())
{
foreach (Cookie cookie1 in response2.Cookies)
{
//string cookie = csrfmiddlewaretoken.ResponseHeaders[HttpResponseHeader.SetCookie];//(response as HttpWebResponse).Headers[HttpResponseHeader.SetCookie];
Console.WriteLine(baseSiteString);
//Console.WriteLine("CSRF Token: {0}", csrfToken);
//Console.WriteLine("Cookie: {0}", cookie);
//
csrfmiddlewaretoken.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
//wc.Headers.Add(HttpRequestHeader.Accept, "application/json, text/javascript, */*; q=0.01");
var csrf1 = cookie1.Value;
string ARG1 = ("100");
string ARG2 = ("5");
string ARG = ("ARG");
string csrfmiddlewaretoken1 =cookie1.Name +"="+cookie1.Value;
csrfmiddlewaretoken.Headers.Add(HttpRequestHeader.Cookie, csrfmiddlewaretoken1);
//string csrf = string.Join(cookie, ARG1, ARG2);
//string dataString =cookie;
// string dataString = #"{""user"":{""email"":"""+uEmail+#""",""password"":"""+uPassword+#"""}}";
string dataString = "{\"ARG1\": \"100\", \"ARG2\": \"5\"}";
// string dataString = "csrftokenmiddlewaretoken="+csrfmiddlewaretoken;
//dataString += "&ARG1=10";
//dataString += "&ARG2=10";
byte[] dataBytes = Encoding.ASCII.GetBytes(dataString);
//byte[] respon2 = csrfmiddlewaretoken.DownloadData(new Uri("http://localhost/api/statusfunction/"));
WebRequest request = WebRequest.Create("http://localhost/api/statusfunction/?ARG");
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
byte[] responseBytes = csrfmiddlewaretoken.UploadData(new Uri("http://localhost/api/multiplyfunction/"), "POST", dataBytes);
string responseString = Encoding.UTF8.GetString(responseBytes);
Console.WriteLine(responseString);
// byte[] res = csrfmiddlewaretoken.UploadFile("http://localhost/api/multiplyfunction/", #"ARG1:100");
// Console.WriteLine(result);
Console.WriteLine("value=" + cookie1.Value);
Console.WriteLine("name=" + cookie1.Name);
Console.WriteLine();
Console.Write((int)response2.StatusCode);
// PostRespone("http://localhost/api/multiplyfunction/");
}
}
}
}
}
Do you accept POST requests in your Django view? If yes, you should use #csrf_exempt decorator for the view that handles POST requests. The other option is to provide CSRF token from C# side.

Python Requests Post Failing With 500 Error

I am using this excellent project on GitHub (https://github.com/cjyoung/MouseBitesWPF). However, that is written in C# and I really need something written in Python. I have boiled that code down to the absolute bare bones of what it needs to work and came up with this:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace DisneyFinderSmaller
{
class Program
{
static CookieContainer cookieJar = new CookieContainer();
static internal string rootUrl = "https://disneyworld.disney.go.com";
static internal string siteUrl = "/dining/";
static internal string diningSearchUrl = "/finder/dining-availability";
static void Main(string[] args)
{
LaunchSearchInstance();
string test = Console.ReadLine();
}
private static void LaunchSearchInstance()
{
string result = getCookiesFromRequest(rootUrl + siteUrl, "", "GET");
string pep_csrf = "";
Match match = Regex.Match(result, "<input[^>]*name=['\"]pep_csrf['\"][^>]*value=['\"]([^'\"]*)['\"]*[^>]>", RegexOptions.Singleline & RegexOptions.IgnoreCase);
pep_csrf = match.Groups[1].ToString();
ConductSearch(pep_csrf);
}
private static void ConductSearch(string pep_csrf)
{
string postString = string.Format("&searchDate={1}" +
"&skipPricing=true" +
"&searchTime={2}" +
"&partySize={3}" +
"&id={0}%3BentityType%3Drestaurant" +
"&type=dining" +
"&pep_csrf={4}",
"293704",
"2015-11-18",
"80000714",
"2",
pep_csrf);
string result = getCookiesFromRequest(rootUrl + diningSearchUrl, postString, "POST");
System.Console.WriteLine(result);
}
private static String getCookiesFromRequest(string url, string postString, string method = "POST")
{
String result = "";
byte[] postBytes = Encoding.ASCII.GetBytes(postString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.Referer = rootUrl + siteUrl;
request.CookieContainer = cookieJar;
if (method == "POST")
{
request.ContentType = "application/x-www-form-urlencoded";
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
}
try
{
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
result = responseStreamReader.ReadToEnd();
responseStream.Close();
webResponse.Close();
}
catch (Exception ex)
{
Console.WriteLine("IOException source: {0}", ex.Source);
}
return result;
}
}
}
In my efforts to translate this to Python using Requests, I have come up with this:
#!/usr/bin/env python
import requests
url = "https://disneyworld.disney.go.com/dining/"
url2 = "https://disneyworld.disney.go.com/dining/finder/dining-availability"
session = requests.Session()
tokenRequest = session.get(url, headers=header)
start = tokenRequest.content.find('''id="pep_csrf"''')
pep = tokenRequest.content[start+21:tokenRequest.content.find('>',start+22)-1]
raw = "&searchDate=2015-11-18&skipPricing=true&searchTime=80000714&partySize=2&id=293704%3BentityType%3Drestaurant&type=dining&pep_csrf=" + pep
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'referer': 'https://disneyworld.disney.go.com/dining/',
'method' : 'POST'
}
result = session.post(url2, data=raw, headers=headers)
print result.status_code
But this doesn't work and returns a status code of 500.
Any thoughts on where things are going wrong? I have been hanging my head against the wall for a few days and any insight at all would be so appreciated.

How to properly make a http web GET request

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

Uploading images to Imgur.com using C#

I just recieve my unique developer API key from Imgur and I'm aching to start cracking on this baby.
First a simple test to kick things off. How can I upload an image using C#? I found this using Python:
#!/usr/bin/python
import pycurl
c = pycurl.Curl()
values = [
("key", "YOUR_API_KEY"),
("image", (c.FORM_FILE, "file.png"))]
# OR: ("image", "http://example.com/example.jpg"))]
# OR: ("image", "BASE64_ENCODED_STRING"))]
c.setopt(c.URL, "http://imgur.com/api/upload.xml")
c.setopt(c.HTTPPOST, values)
c.perform()
c.close()
looks like the site uses HTTP Post to upload images. Take a look at the HTTPWebRequest class and using it to POST to a URL: Posting data with HTTPRequest.
The Imgur API now provide a complete c# example :
using System;
using System.IO;
using System.Net;
using System.Text;
namespace ImgurExample
{
class Program
{
static void Main(string[] args)
{
PostToImgur(#"C:\Users\ashwin\Desktop\image.jpg", IMGUR_ANONYMOUS_API_KEY);
}
public static void PostToImgur(string imagFilePath, string apiKey)
{
byte[] imageData;
FileStream fileStream = File.OpenRead(imagFilePath);
imageData = new byte[fileStream.Length];
fileStream.Read(imageData, 0, imageData.Length);
fileStream.Close();
string uploadRequestString = "image=" + Uri.EscapeDataString(System.Convert.ToBase64String(imageData)) + "&key=" + apiKey;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://api.imgur.com/2/upload");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ServicePoint.Expect100Continue = false;
StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream());
streamWriter.Write(uploadRequestString);
streamWriter.Close();
WebResponse response = webRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(responseStream);
string responseString = responseReader.ReadToEnd();
}
}
}
Why don't you use the NuGet for this: called Imgur.API and for upload
you would have a method like this:
/*
The refresh token and all the values represented by constans are given when you allow the application in your imgur panel on the response url
*/
public OAuth2Token CreateToken()
{
var token = new OAuth2Token(TOKEN_ACCESS, REFRESH_TOKEN, TOKEN_TYPE, ID_ACCOUNT, IMGUR_USER_ACCOUNT, int.Parse(EXPIRES_IN));
return token;
}
//Use it only if your token is expired
public Task<IOAuth2Token> RefreshToken()
{
var client = new ImgurClient(CLIENT_ID, CLIENT_SECRET);
var endpoint= new OAuth2Endpoint(client);
var token = endpoint.GetTokenByRefreshTokenAsync(REFRESH_TOKEN);
return token;
}
public async Task UploadImage()
{
try
{
var client = new ImgurClient(CLIENT_ID, CLIENT_SECRET, CreateToken());
var endpoint = new ImageEndpoint(client);
IImage image;
//Here you have to link your image location
using (var fs = new FileStream(#"IMAGE_LOCATION", FileMode.Open))
{
image = await endpoint.UploadImageStreamAsync(fs);
}
Debug.Write("Image uploaded. Image Url: " + image.Link);
}
catch (ImgurException imgurEx)
{
Debug.Write("Error uploading the image to Imgur");
Debug.Write(imgurEx.Message);
}
}
Also you can find all the reference here: Imgur.API NuGet

Categories