Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- using System.Xml.Linq;
- using System.IO;
- namespace APIHelper
- {
- public static class APITool
- {
- /// <summary>
- /// Generic utility method to build a query string from a dictionary
- /// </summary>
- /// <typeparam name="TKey">Query string variable to be assigned a value</typeparam>
- /// <typeparam name="TValue">Query string value to be assigned to the key</typeparam>
- /// <param name="dict">Dictionary<TKey, TValue> to be passed to the program</param>
- /// <returns>Returns a completed query string, in the form key1=value1&key2=value2</returns>
- public static string BuildQueryString<TKey,TValue>(Dictionary<TKey, TValue> dict)
- {
- //empty query string
- string queryString = "";
- //loop over a key:value pair (hashtable, dict, etc) and build a query string
- foreach (KeyValuePair<TKey, TValue> d in dict)
- {
- queryString += d.Key + "=" + d.Value + "&";
- }
- //Remove trailing & character
- return queryString.Substring(0,queryString.Length-1);
- }
- /// <summary>
- /// Sends a GET request to the URI passed to the constructor.
- /// </summary>
- /// <param name="queryString">Accepts an optional parameter, queryString, which contains a query string of values</param>
- /// <returns>Returns a response from the webserver as a string</returns>
- public static string GET(string uri, string queryString=null)
- {
- WebClient getRequest = new WebClient();
- return getRequest.DownloadString(new Uri(uri + "?" + queryString));
- }
- /// <summary>
- /// Sends a POST request to the URI passed to the constructor
- /// </summary>
- /// <param name="queryString">Accepts optional parameter, queryString, containing a query string to be sent to server</param>
- /// <returns>Returns response from webserver as a string</returns>
- public static string POST(string uri, string queryString = null)
- {
- //New HTTP Request to the URI
- HttpWebRequest postRequest = (HttpWebRequest)WebRequest.Create(new Uri(uri));
- //Response from server
- string response;
- //Convert query string to UTF-8
- byte[] data = Encoding.ASCII.GetBytes(queryString);
- //Set up headers of post request
- postRequest.Method = "POST";
- postRequest.ContentType = "application/x-www-form-urlencoded";
- postRequest.ContentLength = data.Length;
- //Open a stream to write the data
- using (Stream stream = postRequest.GetRequestStream())
- {
- stream.Write(data, 0, data.Length);
- }
- //Get response from server and return it as a string
- using (HttpWebResponse HTTPResponse = (HttpWebResponse)postRequest.GetResponse())
- using (Stream stream = HTTPResponse.GetResponseStream())
- using (StreamReader reader = new StreamReader(stream))
- {
- response = reader.ReadToEnd();
- }
- return response;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement