How to properly make a http web GET request - c#

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

Related

How to make a http web asyncGET request

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

Convert C# from full framework to core with WebRequest

I’m not overly awesome with my C# but was hoping if someone could help me with my code snippet here.
First one works fine in C# full .net framework, the second one is where I tried to change the first over to dotnet core (standard 1.3), but it just doesn’t work and seems to barf out on “using (Stream stream = response.GetResponseStream())” with “"errorMessage": "The remote server returned an error: (400) Bad Request.", but no idea why.
I assume it has something to do with the *async calls, but really not sure.
Thanks already and help is much appreciated.
public static string AcquireTokenBySpn(string tenantId, string clientId, string clientSecret)
{
var payload = String.Format(SpnPayload, WebUtility.UrlEncode(ArmResource), WebUtility.UrlEncode(clientId),
WebUtility.UrlEncode(clientSecret));
byte[] data = Encoding.ASCII.GetBytes(payload);
var address = String.Format(TokenEndpoint, tenantId);
WebRequest request = WebRequest.Create(address);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
if (stream != null)
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
JObject jObject = JObject.Parse(responseContent);
return (string)jObject["access_token"];
}
This is the "core snippet".
public static async Task<string> AcquireTokenBySpn(string tenantId, string clientId, string clientSecret, double apiVersion)
{
var payload = String.Format(SpnPayload, WebUtility.UrlEncode(clientId),
WebUtility.UrlEncode(clientSecret));
var data = Encoding.ASCII.GetBytes(payload);
var address = String.Format(TokenEndpoint, tenantId, apiVersion);
WebRequest request = WebRequest.Create(address);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//request. ContentLength = data.Length;
using (Stream stream = await request.GetRequestStreamAsync())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream stream = response.GetResponseStream())
{
if (stream != null)
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
JObject jObject = JObject.Parse(responseContent);
return (string)jObject["access_token"];
}
}
The error sure is related to to GetResponseAsync(). You need to check what is happening over there.
BTW. it is much better to work with .NETCore 2.0 rather than 1.3 as it has a vere huger library support as it supports .NET Standard 2.0 libraries.

Getting the response of Asynchronous http web request using POST method in asp.net core

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

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.

calling google Url Shortner API in 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;
}

Categories