I have some code that formats a JSON request using RestSharp to access ESRI geocoding API. The code works, but I'm wondering if there is a better way to get the request into the correct format here is a sample of what I have and below a sample of what the request should look like.
request = new RestRequest("geocodeAddresses", Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//Format the request properly
var attributes = new Dictionary<string, object>();
attributes.Add("OBJECTID", address.Address);
attributes.Add("Address", address.Address);
attributes.Add("City", address.City);
attributes.Add("Region", address.State);
attributes.Add("Postal", address.ZipCode);
JsonObject attributesObj = new JsonObject();
foreach (var parms in attributes)
{
attributesObj.Add(parms);
}
JsonObject recordsObj = new JsonObject();
recordsObj.Add("attributes", attributesObj);
JsonArray EsriRequest = new JsonArray();
EsriRequest.Add(recordsObj);
JsonObject addressObj = new JsonObject();
addressObj.Add("records", EsriRequest);
request.AddParameter("addresses",
addressObj.ToString());
request.AddParameter("token", esriToken.ToString());
request.AddParameter("f", "json");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
IRestResponse<EsriAddress> responseData = client.Execute<EsriAddress>(request);
Request output sample:
http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/geocodeAddresses?addresses={"records":[{"attributes":{"OBJECTID":1,"Address":"380 New York St.","City":"Redlands","Region":"CA","Postal":"92373"}},{"attributes":{"OBJECTID":2,"Address":"1 World Way","City":"Los Angeles","Region":"CA","Postal":"90045"}}]}&sourceCountry=USA&token=<YOUR TOKEN>&f=pjson
I currently only ever send one address, but in theory the api can take more then one at a time.
Here's how I send a batch of addresses to the geocodeAddresses method in the ArcGIS REST API. I'm not using RestSharp, just HttpClient:
string token = GetToken();
string url = "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/geocodeAddresses";
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("token", token),
new KeyValuePair<string, string>("forStorage", "true"),
new KeyValuePair<string, string>("MaxBatchSize", "1000"),
new KeyValuePair<string, string>("outFields", "*"),
new KeyValuePair<string, string>("f", "json"),
new KeyValuePair<string, string>("addresses", inputJson) // json string containing an array of a complex type
};
foreach (var keyValuePair in values)
content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
var response = await client.PostAsync(url, content);
Task<string> responseString = response.Content.ReadAsStringAsync();
string outputJson = await responseString;
}
}
Related
Hello, I am pulling data from an api with C# HttpClient. I need to pull data in form-data form with the post method. I wrote the code below but got an empty response. How can I do it?
var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(300);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = new Uri("https://myapi.com");
var content = new MultipartFormDataContent();
var dataContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("value1", "myvalue1"),
new KeyValuePair<string, string>("value2", "myvalue2"),
new KeyValuePair<string, string>("value3", "myvalue3")
});
content.Add(dataContent);
request.Content = content;
var header = new ContentDispositionHeaderValue("form-data");
request.Content.Headers.ContentDisposition = header;
var response = await client.PostAsync(request.RequestUri.ToString(), request.Content);
var result = response.Content.ReadAsStringAsync().Result;
You're sending your data in an incorrect way by using FormUrlEncodedContent.
To send your parameters as MultipartFormDataContent string values you need to replace the code below:
var dataContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("key1", "myvalue1"),
new KeyValuePair<string, string>("key2", "myvalue2"),
new KeyValuePair<string, string>("key3", "myvalue3")
});
With this:
content.Add(new StringContent("myvalue1"), "key1");
content.Add(new StringContent("myvalue2"), "key2");
content.Add(new StringContent("myvalue3"), "key3");
I have been provided an API with the base URL and the Authentication URL. This API makes use of token authentication. I have written code to authenticate then pass the token to the other URL but keep running into the error below:
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.'
My code is as below
public string Index()
{
var accessToken = string.Empty;
string URL = "https://api.mkoinapp.net/apps/merchants/api/v1/auth/apps/authenticate/";
string _user = "XX";
string _pwd = "XX";
string _clientId = "XXX";
string _clientSecret = "XXXX";
var KeyValus = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", _user),
new KeyValuePair<string, string>("password", _pwd),
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("client_id", _clientId),
new KeyValuePair<string, string>("client_secret", _clientSecret)
};
var request = new HttpRequestMessage(HttpMethod.Post, URL + "access_token");
request.Content = new FormUrlEncodedContent(KeyValus);
var client = new HttpClient();
var response = client.SendAsync(request).Result;
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(json);
// List<Token> jwtDynamic = JsonConvert.DeserializeObject<List<Token>>(json);
var accessTokenExpiration = jwtDynamic.Value<DateTime>("expires_in");
accessToken = jwtDynamic.Value<string>("access_token");
var name = jwtDynamic.Value<string>("name");
var accessexpirationDate = accessTokenExpiration;
Response.Redirect("https://api.mkoinapp.net/apps/merchants/api/v1/iprs?id=" + _user);
}
return accessToken;
}
Any help to resolve this will be apprciated.
You may be experiencing any of these errors:
The response is a bad formatted JSON.
The response is not a JSON (could be an HTML as Casey is mentioning or XML).
The response is an array, you're trying to parse JObject in that case you're going to need JArray.
When I try in postman it working fine and I am getting a response.
I am trying to make a request. and I am not getting any response please look into my code and let me know where I did wrong?
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("client_id", "11223asda"),
new KeyValuePair<string, string>("client_secret", "1232asdasa"),
new KeyValuePair<string, string>("code", "authcode3"),
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("redirect_uri", "http://www.google.com/")
});
var uri = new Uri("https://sandbox-api.userdomain.com/v2/oauth2/token");
// var content = new FormUrlEncodedContent(obj);
//HttpResponseMessage response = null;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
Debug.WriteLine(response.StatusCode);
Output :
For this type of work I use this lib :
https://github.com/jgiacomini/Tiny.RestClient
var client = new TinyRestClient(new HttpClient(),"https://sandbox-api.userdomain.com/");
var response = await client.
PostRequest("v2/oauth2/token").
AddFormParameter("client_id", "France").
AddFormParameter("client_secret", "Paris").
AddFormParameter("grant_type", "Paris").
AddFormParameter("redirect_uri", "Paris").
ExecuteAsync<Response>();
Hope that helps!
i'm trying to send a post request to an online API to recieve net data, it was succesfull with normal key-value's but not with array's as value and i could't find it on the internet without creating a big amount of extra classes.
This is how i tried to post to the url with normal data (the 3th one needs an array in stead of a single object).
IEnumerable<KeyValuePair<string, string>> queries = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("keyA","ValueA"),
new KeyValuePair<string, string>("keyB", ""),
new KeyValuePair<string, string>("KeyC", "ValueCDE"), //array
};
HttpContent q = new FormUrlEncodedContent(queries);
Console.WriteLine(q.ToString());
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.PostAsync(url, q))
{
using (HttpContent content = response.Content)
{
string mycontent = await content.ReadAsStringAsync();
HttpContentHeaders headers = content.Headers;
Console.WriteLine(mycontent);
Console.WriteLine(response);
}
}
}
I tried to send raw data to the url but i recieved no response from it.
async static void PostRawRequest(string url)
{
string rawr = #"{
""a"":""a"",
""b"":"""",
""c"": [""C"", ""D"",""F""],
""StickerColor"": ""red""
}";
string result = "";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString(url, "POST", rawr);
}
Console.WriteLine(result);
}
Can anyone help me in either the first(sending array values) or second (sending raw data)?
If you can, use a library to handle the serialization for you. Then you can do something like this (using Newtonsoft.Json):
using (var client = new HttpClient())
{
var json = JsonConvert.SerializeObject(yourObject);
client.PostAsync(yourUri, new StringContent(json, Encoding.UTF8, "application/json"));
}
I am currently developing a wp8.1 application C#, i have managed to perform a POST method in json to my api by creating a json object (bm) from textbox.texts.
here is my code below. How do i take the same textbox.text and POST them as a content type = application/x-www-form-urlencoded. whats the code for that?
Profile bm = new Profile();
bm.first_name = Names.Text;
bm.surname = surname.Text;
string json = JsonConvert.SerializeObject(bm);
MessageDialog messageDialog = new MessageDialog(json);//Text should not be empty
await messageDialog.ShowAsync();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
byte[] messageBytes = Encoding.UTF8.GetBytes(json);
var content = new ByteArrayContent(messageBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync("myapiurl", content).Result;
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Input1", "TEST2"));
nvc.Add(new KeyValuePair<string, string>("Input2", "TEST2"));
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
Or
var dict = new Dictionary<string, string>();
dict.Add("Input1", "TEST2");
dict.Add("Input2", "TEST2");
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);
var params= new Dictionary<string, string>();
var url ="Please enter URLhere";
params.Add("key1", "value1");
params.Add("key2", "value2");
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(params)).Result;
var token = response.Content.ReadAsStringAsync().Result;
}
//Get response as expected
The best solution for me is:
// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");
// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}
Another variant to POST this content type and which does not use a dictionary would be:
StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
string resultJson = result.Content.ReadAsStringAsync().Result;
}