Http Post C# with Json response - c#

I would like to get a method that generates an http post with the following configuration in c#.
POST pqs.php HTTP/1.1
Host: nationalmap.gov/epqs/pqs.php
Content-Type: application/x-www-form-urlencoded
Content-Length: length
x=string&y=string&units=string&output=string
I tried the following however I am getting invalid coordinates although they do exist in the map ( example tried is lat = 36.574832 and lon = -85.411825
Here is the code I am using:
public class ElevationUSGISPull
{
public string responseString = null;
private string BASEURL = "http://nationalmap.gov/epqs/pqs.php";
public bool httpPostElevationRequest( string lon,string lat)
{
try
{
using (WebClient client = new WebClient())
{
byte[] response =
client.UploadValues(BASEURL, new NameValueCollection()
{
{ "x", lon },
{ "y", lat },
{"units", "feet" },
{"output","json" },
});
string result = System.Text.Encoding.UTF8.GetString(response);
responseString = result;
}
return true;
}
catch(Exception eX)
{
return false;
}
}
}
The error I am getting is as below:
<error>General failure: Invalid Coordinates</error>
Moreover has anyone tried the .gov website to get elevation data. I used the google server however it has many restrictions related to number of requests and I am trying to do many requests for a given area.
Below is a website for verifying the lat and longs with a good json response.
https://nationalmap.gov/epqs/
Thanks all.
I have also tried the following example here:
http://ronaldrosiernet.azurewebsites.net/Blog/2013/12/07/posting_urlencoded_key_values_with_httpclient
But is giving me the following error.
Exception thrown: 'System.NullReferenceException'
I modified the code to this:
public async Task<string> HTTPPOST(string lon, string lat)
{
var client = new HttpClient();
client.BaseAddress = new Uri(BASEURL);
var request = new HttpRequestMessage(HttpMethod.Post, "");
var keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("x", lon));
keyValues.Add(new KeyValuePair<string, string>("y", lat));
keyValues.Add(new KeyValuePair<string, string>("units", "feet"));
keyValues.Add(new KeyValuePair<string, string>("output", "json"));
request.Content = new FormUrlEncodedContent(keyValues);
var response = await client.SendAsync(request);
return response.ToString();
}

After debugging for an hour I noticed that I had units as a parameter rather than unit :( ......
public string httpPostElevationRequest( string lon,string lat)
{
try
{
using (WebClient client = new WebClient())
{
byte[] response =
client.UploadValues(BASEURL, new NameValueCollection()
{
{ "x", lon },
{ "y", lat },
{"unit", "feet" },
{"output","json" },
});
string result = System.Text.Encoding.UTF8.GetString(response);
responseString = result;
}
return responseString;
}
catch(Exception eX)
{
return null;
}
}
Also baseurl is as follows:
private string BASEURL = "https://nationalmap.gov/epqs/pqs.php";

Use .NET HttpClient
Find an example here

Related

Error 401 'INVALID_KEY_TYPE' with FireBase and c#

I am implementing c # with FireBase, it sends me error 401 'INVALID_KEY_TYPE'
private static Uri FireBasePushNotificationsURL = new Uri("https://fcm.googleapis.com/fcm/send");
private static string ServerKey = "AIzaSyA9fL8lPyxcrngIDDsDeUbq9sPTkavXXXX";
public static async Task<bool> SendPushNotification(string deviceTokens, string title, string body, object data)
{
bool sent = false;
if (deviceTokens.Count() > 0)
{
//Object creation
var messageInformation = new
{
to = "fZ0EyxU-tsk:APA91bE3-qo4DwL9phteDJC8pG6iLdr-YSSl-N_2SJne3U6eyUhmEuZNQhJi0YM-XXXXXX",
priority = "high",
content_available = true,
notification = new
{
body = "Test",
title = "Test miguel",
badge = 1
},
};
//Object to JSON STRUCTURE => using Newtonsoft.Json;
string jsonMessage = JsonConvert.SerializeObject(messageInformation);
//Create request to Firebase API
var request = new HttpRequestMessage(HttpMethod.Post, FireBasePushNotificationsURL);
request.Headers.TryAddWithoutValidation("Authorization", "key=" + ServerKey);
request.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
HttpResponseMessage result;
using (var client = new HttpClient())
{
result = await client.SendAsync(request);
sent = sent && result.IsSuccessStatusCode;
}
}
return sent;
}
I have the same problem. The problem is that you take the wrong server key.
The right firebase server key is Project > Settings > Cloud Messaging > Server Key

HttpClient post request for WebApi using asp.net mvc application

I'm trying to consume WebApi but I'm having issues. My 'IsSuccessStatusCode' is always false and I have 404 in response.
I have tried multiple methods but can't be able to do it correctly.
Constants:
const string baseUri = ""; // base url of API
const string setDealFlagUri = "Deals/SetDealFlag";
Method 1, using PostAsync:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUri);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("deadId", "3"),
new KeyValuePair<string, string>("flagValueToSet", "true")
});
var response = await client.PostAsync(setDealFlagUri, content);
if (response.IsSuccessStatusCode)
{
return true;
}
}
Method 2, using PostAsJsonAsync:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUri);
DealFlag content = new DealFlag
{
deadId = 3,
flagValueToSet = true
};
var response = await client.PostAsJsonAsync(setDealFlagUri, content);
if (response.IsSuccessStatusCode)
{
return true;
}
}
WebApi request detail:
Curl:
curl -X POST --header 'Accept: application/json' '{baseApiurl}/Deals/SetDealFlag?dealId=3&flagValueToSet=true'
Request URL
{baseApiurl}/Deals/SetDealFlag?dealId=3&flagValueToSet=true
Response Body
{
"Successful": true,
"ErrorMessages": [],
"ValidationResults": {
"IsValid": false,
"ValidationErrors": []
}
}
Response Headers
{
"pragma": "no-cache",
"date": "Wed, 24 Aug 2016 18:38:01 GMT",
"content-encoding": "gzip",
"server": "Microsoft-IIS/8.0",
"x-aspnet-version": "4.0.30319",
"x-powered-by": "ASP.NET",
"vary": "Accept-Encoding",
"content-type": "application/json; charset=utf-8",
"cache-control": "no-cache",
"content-length": "198",
"expires": "-1"
}
Please help me to use this webapi function correctly.
Thanks!
I think that the problem is that your controller method has signature like
[HttpPost]
public HttpResponseMessage SetDealFlag(int dealId, bool flagValueToSet)
Am I right? If your answer is "Yes" so your method wants parameters in the URL.
And so you get 404 error becouse no one of yours Web API methods matches to that URL.
Send your parameters dealId and flagValueToSet in the URL is the solution.
I wrote simple console app for testing my theory and it works perfectly:
public static void Main(string[] args)
{
using (var client = new HttpClient())
{
try
{
// Next two lines are not required. You can comment or delete that lines without any regrets
const string baseUri = "{base-url}";
client.BaseAddress = new Uri(baseUri);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("deadId", "3"),
new KeyValuePair<string, string>("flagValueToSet", "true")
});
// response.Result.IsSuccessStatusCode == true and no errors
var response = client.PostAsync($"{baseUri}/Deals/SetDealFlag?dealId=3&flagValueToSet=true", null);
// response.Result.IsSuccessStatusCode == false and 404 error
// var response = client.PostAsync($"{baseUri}/Deals/SetDealFlag", content);
response.Wait();
if (response.Result.IsSuccessStatusCode)
{
return;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}

Adding subscribers to a list in Mail Chimp 3.0 in ASP.NET

I am trying to implement Mail Chimp's new API with my ASP.NET C# website so when a user enters their email address into an input box it will be added to my mailchimp list automatically. I have tried various other methods however none of these have worked.
I have tried a Web Client which threw a 405 Cannot use that Method response and a HttpClient which threw an error on the starred GetStringAsync method call because its not a task.
My code so far is detailed below:
public bool BatchSubscribe(IEnumerable<MailChimpSubscriberModel> newSubscribers)
{
if (string.IsNullOrEmpty(_defaultListId)) throw new ArgumentNullException(Res.Resource.MailChimpIntegrationNoListId);
if (string.IsNullOrEmpty(_apiKey)) throw new ArgumentNullException(Res.Resource.MailChimpIntegrationNoApiKey);
foreach (MailChimpSubscriberModel subscriber in newSubscribers)
{
string url = "https://" + _dataPoint + ".api.mailchimp.com/3.0/lists/" + _defaultListId + "/";
Subscriber member = new Subscriber();
member.email = subscriber.Email;
member.subscribed = "subscribed";
string jsonString = new JavaScriptSerializer().Serialize(member);
//using (WebClient client = new WebClient())
//{
// client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
// client.Headers[HttpRequestHeader.Authorization] = new AuthenticationHeaderValue("Basic", _apiKey).ToString();
// string HtmlResult = client.(url, jsonString);
// return true;
//}
using (var http = new HttpClient())
{
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", _apiKey);
string content = await http.**GetStringAsync**(#"https://us11.api.mailchimp.com/3.0/lists");
Console.WriteLine(content);
}
}
return false;
}
I'm a bit late to this question, but as it took me half a day to figure it out, here there is my answer, so it can help others. I'm using MailChimp 3.0:
private void subscribeAddress()
{
string apiKey = "APIKEY-usX"; //your API KEY created by you.
string dataCenter = "usX";
string listID = "listID"; //The ListID of the list you want to use.
SubscribeClassCreatedByMe subscribeRequest = new SubscribeClassCreatedByMe
{
email_address = "somebodys#email.com",
status = "subscribed"
};
subscribeRequest.merge_fields = new MergeFieldClassCreatedByMe();
subscribeRequest.merge_fields.FNAME = "YourName";
subscribeRequest.merge_fields.LNAME = "YourSurname";
using (HttpClient client = new HttpClient())
{
var uri = "https://" + dataCenter + ".api.mailchimp.com/";
var endpoint = "3.0/lists/" + listID + "/members";
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", apiKey);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(uri);
//NOTE: To avoid the method being 'async' we access to '.Result'
HttpResponseMessage response = client.PostAsJsonAsync(endpoint, subscribeRequest).Result;//PostAsJsonAsync method serializes an object to
//JSON and then sends the JSON payload in a POST request
//StatusCode == 200
// -> Status == "subscribed" -> Is on the list now
// -> Status == "unsubscribed" -> this address used to be on the list, but is not anymore
// -> Status == "pending" -> This address requested to be added with double-opt-in but hasn't confirmed yet
// -> Status == "cleaned" -> This address bounced and has been removed from the list
//StatusCode == 404
if ((response.IsSuccessStatusCode))
{
//Your code here
}
}
}
Here there are the classes SubscribeClassCreatedByMe and MergeFieldClassCreatedByMe
namespace Subscriber
{
public class SubscribeClassCreatedByMe
{
public string email_address { get; set; }
public string status { get; set; }
public MergeFieldClassCreatedByMe merge_fields { get; set; }
}
}
namespace Subscriber
{
public class MergeFieldClassCreatedByMe
{
public string FNAME { get; set; }
public string LNAME { get; set; }
}
}
Well, I hope this help!!
401 isn't "cannot use that method" it's "Unauthorized". You've got an authentication error. From the looks of things, you're not quite doing basic auth the right way. Check out this example for the details you're missing.
PS: the response that comes back from APIv3 is usually pretty helpful, so you should always make sure to look at that whole response, not just the status code.
It works if you change auth to these lines:
String username = "abc"; //anything
String password = apiKey; //your apikey
String encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encoded);
Below code snippet is should work on .NET Core 2.1 using Mailchimp API V3.0:
string url = #"https://" + mailchimpInstance + ".api.mailchimp.com/3.0/lists/" + ListId + "/members";
var info = new Info() { email_address = "example#gmail.com", status = "subscribed" };
var infoJson = JsonConvert.SerializeObject(info);
using (var client = new HttpClient())
{
var uri = "https://" + mailchimpInstance + ".api.mailchimp.com/";
var endpoint = "3.0/lists/" + ListId + "/members";
try
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",ApiKey);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(uri);
var content = new StringContent(infoJson.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(endpoint, content);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response from server -> " + responseString);
return Ok();
Add into References MailChimp.Net.dll
than you can define an interface like
IMailChimpManager manager = new MailChimpManager(ConfigurationManager.AppSettings["MailChimpApiKey"].ToString());
than you can add or update your client in your MailChimp list
Member m = await manager.Members.AddOrUpdateAsync(ConfigurationManager.AppSettings["MailChimpListId"].ToString(), new Member { EmailAddress = _email, EmailType = "html", Status = Status.Pending});
m = await manager.Members.AddOrUpdateAsync(ConfigurationManager.AppSettings["MailChimpListId"].ToString(), new Member { EmailAddress = _email, EmailType = "html", Status = Status.Subscribed });
It is very simple.. I think...

best practice for uploading images to azure blob

I am building a mobile app using xamarin while the server is hosted in azure. I am uploading images in the following way:
Client:
public static async Task<string> UploadImage (string url, byte[] imageData)
{
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(imageData);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = Guid.NewGuid() + ".Png"
};
content.Add(fileContent);
using (var client = new HttpClient())
{
try
{
HttpResponseMessage msg = await client.PutAsync (url, content);
if(msg.StatusCode == System.Net.HttpStatusCode.OK)
{
return msg.Headers.GetValues ("ImageUrl").First();
}
return string.Empty;
}
catch (Exception ex)
{
return string.Empty;
}
}
}
and here is the server code:
[HttpPut]
public async Task<HttpResponseMessage> PostNewDishImage(string imageID)
{
try
{
_dishImagescontainer = BlobStorageHandler.GetContainer("dishuserimages");
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
var provider = new BlobStorageProvider(_dishImagescontainer);
await Request.Content.ReadAsMultipartAsync(provider);
IList<string> urls = provider.Urls;
if (urls.Count > 0)
{
var response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Headers.Add("ImageUrl", urls[0]);
return response;
}
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
catch (System.Exception e)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError) { ReasonPhrase = e.ToString() };
}
}
It works fine but I don't like the way I am returning the new imageurl back to the client (through the http headers) I have tried some other ways but this is the best one so far :)
Does anyone have any better ideas?
Thanks
Returning data to the client in an HTTP header like that does have a bit of a smell. How about returning a DTO serialized to JSON?
An example DTO class:
public class ImageUploadResponse
{
public string Url { get; set; }
}
Then change your server side code to something like this:
var responseDto = new ImageUploadResponse { Url = urls[0] };
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(JsonConvert.SerializeObject(responseDto),
Encoding.UTF8, "application/json")
};
which will send the results back to the client in the content of the HTTP response as JSON. Then the client can parse the JSON into an object (or not) as you see fit. This approach will also be more friendly to making such a call from JavaScript in the future if you desire because the result is standard JSON.

C# application/x-www-form-urlencoded OAuth and HTTP REST requests using HttpClient

So I'm trying to put together some very simple and elegant code samples to help people use my API. The latest language I'm tackling is C#.
I think the IETF OAuth2.0 standard I read implies the HTTP request Content-Type must be "application/x-www-form-urlencoded". The Django API server I have, currently seems to only support this Content-Type (for the OAuth resource). The other languages POST content this way by default!
After extensive research and several experiments I am wondering if I have missed something fundamental. Surely there would be a helpful library OR technique to create the ...urlencoded string OR at least someone else must have run into this???
I will outline some of the best solution I have so far bellow, but it just seems wrong.
Also from a bunch of internet browsing I figured I would use the HttpClient library. I like the fact that it uses the async model, which perhaps will be more useful for any developers using WPF or XAML or Windows 8 apps. It also works well for Consoles and Forms.
I use the Newtonsoft Json.Net library for serialization. First of all I create a POCO of the authorization strings. Then I serialize it to JSON, then to key/value pairs, then iterate through the key/value pairs catenating with the required '=' and '&' chars, then UTF-8, then escape the spaces etc.
//Setup HTTP request
HttpClient httpRequest = new HttpClient();
httpRequest.DefaultRequestHeaders.Add("Accept", "application/json");
string urlBase = "https://__secret__/api/v1/";
HttpResponseMessage msg = new HttpResponseMessage();
//POST to oauth to get token (must be sent as "application/x-www-form-urlencoded")
OAuthConfig oAuthCredentials = new OAuthConfig { client_id = client_id, client_secret = secret, username = "__secret__", password = "__secret__", grant_type = "__secret__" };
string jsonString = JsonConvert.SerializeObject(oAuthCredentials); //convert to JSON
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString); //convert to key/value pairs
string urlEncodedData = ConvertToFormUrlEncodedFormat(values);
HttpContent payload = new StringContent(urlEncodedData, Encoding.UTF8, "application/x-www-form-urlencoded");
msg = httpRequest.PostAsync(urlBase + "oauth/access_token/", payload).Result;
string responseBodyAsText = msg.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseBodyAsText);
Other options I could think of were...
Reflection, however digging into reflection in a code sample seems a bit manic.
It turns out that other than the OAuth setup, the rest of the API supports JSON type POSTs. So I guess I could write a function to walk through the oAuthConfig model and catenate a string, since that POCO model is unlikely to change and is the only model which requires urlEncoding that I can anticipate. That would save us from the slightly confusing use of the Dictionary. The use of the dictionary and then iterating is more generic, however perhaps a bit OTT.
I figure most of the time people will be using JSON, so showing how that might happen is useful.
In general it seems quite hard to serialize a POCO model to a string and/or to a urlEncoded string.
Questions
does OAuth mandate urlencoded, could you convert server-side?
is HttpClient the best choice, does async matter?
is there a better simpler way to serialize a POCO to ...form-urlencoded?
Thanks for any useful comments you may have.
var model = new LoginModel { Username = "patient#gmail.com", Password = "123456", DeviceId = "123456789", RoleId = 1 };
url.Append("/Login");
string data = JsonConvert.SerializeObject(model);// "{\"username\":\"dscdemo0#gmail.com\",\"password\":\"vipin123\"}";
NameValueCollection inputs = new NameValueCollection();
inputs.Add("json", data);
WebClient client = new WebClient();
var reply = client.UploadValues(url.ToString(), inputs);
string temp = Encoding.ASCII.GetString(reply);
var result = JsonConvert.DeserializeObject<MessageTemplateModel>
(temp);
Api Call
public async Task<IHttpActionResult> Login(HttpRequestMessage request)//(LoginModel modelN)
{
try
{
var form = request.Content.ReadAsFormDataAsync().Result;
var modelN = JsonConvert.DeserializeObject<LoginModel>(form["json"].ToString());
// token = JsonConvert.DeserializeObject<string>(form["token"].ToString());
bool istoken = _appdevice.GettokenID(modelN.DeviceId);
if (!istoken)
{
statuscode = 0;
message = ErrorMessage.TockenNotvalid;
goto invalidtoken;
}
User model = new User();
// var session = HttpContext.Current.Session;
// session.Add("UserRole", GetProfileId.UserRole);
var user = await _userManager.FindAsync(modelN.Username, modelN.Password);}}
i am able to call url-encoder request from device and web app.
//I disclaimer everything and note that I haven't re-checked if this posted code works.
using System;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json; //install with Nuget package installer- "json.Net"
using System.Net.Http; //install with Nuget package installer- "...Web API client libraries"
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json; //security risk till certificate fixed
namespace CSharpDemoCodeConsole
{
class Program
{
const string api_key = "your_api_key"; //set your api_key here
const string user_auth = "your_username" + ":" + "your_password"; // set your user credentials here
const string urlBase = "https://#SECRET.com#/api/v1";
static void Main(string[] args)
{
Console.WriteLine("Making call to webserver asynchronously");
MakeCallAsynchronously();
Console.WriteLine("**************************************");
Console.WriteLine("Making call to webserver synchronously");
MakeCallSynchronously();
Console.WriteLine("**************************************");
Console.WriteLine("Making call to webserver synchronously without Newtonsoft serialization");
MakeCallSynchronouslyWithoutNewtonSoft();
Console.WriteLine("Press spacebar to close the application");
Console.ReadKey();
}
private static void MakeCallAsynchronously()
{
//Always accept untrusted certificates - don't use in production
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//Setup request
string authorizeString = Convert.ToBase64String(Encoding.ASCII.GetBytes(user_auth));
HttpClient httpRequest = new HttpClient();
httpRequest.DefaultRequestHeaders.Add("Authorization", "Basic " + authorizeString);
httpRequest.DefaultRequestHeaders.Add("Accept", "application/json");
//GET from places resource
try
{
var requestTask = httpRequest.GetAsync(urlBase + "places/" + "?api_key=" + api_key,
System.Net.Http.HttpCompletionOption.ResponseContentRead);
//Update UI while waiting for task to complete
while (requestTask.Status != System.Threading.Tasks.TaskStatus.RanToCompletion)
{
Console.Write(".");
System.Threading.Thread.Sleep(30);
}
if (requestTask.Result.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("Unexpected response from server: {0}", requestTask.Result);
return;
}
var places = JsonConvert.DeserializeObject<Page<Place>>(requestTask.Result.Content.ReadAsStringAsync().Result);
Console.WriteLine("GET places response " + requestTask.Result.Content.ReadAsStringAsync().Result);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return;
}
//POST to places resource
try
{
string jsonString = JsonConvert.SerializeObject(new Place { name = "test place", latitude = 0, longitude = 0 });
HttpContent payload = new StringContent(jsonString, Encoding.UTF8, "application/json");
var requestTask = httpRequest.PostAsync(urlBase + "places/" + "?api_key=" + api_key, payload);
//Update UI while waiting for task to complete
while (requestTask.Status != System.Threading.Tasks.TaskStatus.RanToCompletion)
{
Console.Write(".");
System.Threading.Thread.Sleep(30);
}
if (requestTask.Result.StatusCode != HttpStatusCode.Created)
{
Console.WriteLine("Unexpected response from server: {0}", requestTask.Result);
return;
}
Console.WriteLine("POST places response " + requestTask.Result.Content.ReadAsStringAsync().Result);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return;
}
}
private static void MakeCallSynchronously()
{
//Always accept untrusted certificates - don't use in production
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//Setup Request
string authorizeString = Convert.ToBase64String(Encoding.ASCII.GetBytes(user_auth));
var client = new WebClient();
client.Headers.Add("Authorization", "Basic " + authorizeString);
client.Headers.Add("Accept", "application/json");
//GET from places resource
try
{
var responseStream = client.OpenRead(urlBase + "places/" + "?api_key=" + api_key);
var response = (new StreamReader(responseStream).ReadToEnd());
var places = JsonConvert.DeserializeObject<Page<Place>>(response);
Console.WriteLine("GET places response " + response);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
}
//POST to places resource
try
{
client.Headers.Add("Accept", "application/json");
client.Headers.Add("Content-Type", "application/json");
string jsonString = JsonConvert.SerializeObject(new Place { name = "test place", latitude = 0, longitude = 0 });
client.Encoding = System.Text.Encoding.UTF8;
string response = client.UploadString(urlBase + "places/" + "?api_key=" + api_key, jsonString);
Console.WriteLine("POST places response " + response);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return;
}
}
private static void MakeCallSynchronouslyWithoutNewtonSoft()
{
//Always accept untrusted certificates - don't use in production
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//Setup Request
string authorizeString = Convert.ToBase64String(Encoding.ASCII.GetBytes(user_auth));
var client = new WebClient();
client.Headers.Add("Authorization", "Basic " + authorizeString);
client.Headers.Add("Accept", "application/json");
//GET from places resource
try
{
var responseStream = client.OpenRead(urlBase + "places/" + "?api_key=" + api_key);
MemoryStream ms = new MemoryStream();
responseStream.CopyTo(ms);
ms.Position = 0;
var placesDeserializer = new DataContractJsonSerializer(typeof(Page<Place>));
var places = (Page<Place>)placesDeserializer.ReadObject(ms);
ms.Position = 0;
string response = (new StreamReader(ms).ReadToEnd());
ms.Close();
Console.WriteLine("GET places response " + response);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return;
}
//POST to places resource
try
{
client.Headers.Add("Accept", "application/json");
client.Headers.Add("Content-Type", "application/json");
DataContractJsonSerializer placesSerializer = new DataContractJsonSerializer(typeof(Place));
Place place = new Place { name = "test place", latitude = 0, longitude = 0 };
MemoryStream ms = new MemoryStream();
placesSerializer.WriteObject(ms, place);
byte[] json = ms.ToArray();
ms.Close();
string jsonString = Encoding.UTF8.GetString(json, 0, json.Length);
client.Encoding = System.Text.Encoding.UTF8;
string response = client.UploadString(urlBase + "places/" + "?api_key=" + api_key, jsonString);
Console.WriteLine("POST places response " + response);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
return;
}
}
}
public class Place
{
[JsonProperty("url")]
public string url { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("latitude")]
public float latitude { get; set; }
[JsonProperty("longitude")]
public float longitude { get; set; }
}
public class Page<T>
{
[JsonProperty("count")]
public int count { get; set; }
[JsonProperty("next")]
public string next { get; set; }
[JsonProperty("previous")]
public string previous { get; set; }
[JsonProperty("results")]
public List<T> results { get; set; }
}
}

Categories