I have a c# object: a list with objects (objects have ID and Name)
Now I need to include the list of objects (it should be json string as far as I understand) in URL as parameter. How is it possible to do it?
If I understand you correctly, you need this.
var client = new WebClient();
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
string response = client.UploadString("http://mysite", "json string");
Related
I have been using some simple requests in past to send JSON and they have been working fine. I basically take simple string, convert it to UTF-8 using
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
and send this using HttpWebRequest.
Now I have received a task to send a new POST request which will have an array of Ids and be of type
{
"GroupID": "Named_ID",
"ChildIds": [
"76197272-24E4-4DD2-90B8-46FDDCC0D6CA",
"D2B3A1AC-ACF6-EA11-A815-000D3A49E4F3",
"ED53D968-00F4-EA11-A815-000D3A49E4F3"
]
}
The ChildIds are available in a List(String []) with me. I could loop through the records and create a similar long string and then convert to byteArray in UTF8 but I feel this can be done in a simpler way. Examples that I have seen on the forum of using array in JSON always appear to use JsonConvert.SerializeObject but I am not clear if I should use this and if I do then do I convert the serialised object to UTF8 like I did earlier and is it then ok to use in the HttpWebRequest.
Can someone please advice on the approach I should take.
Create a class structure to match your json,
public class Data
{
public string GroupId {get;set;}
public List<string> ChildIds {get;set;}
}
serialize the data with JsonConvert or any other.
var json = JsonConvert.SerializeObject<Data>(str) ;
Post the serialized data with httpclient assuming you have it injected in your class already.
var data = new StringContent(json, Encoding.UTF8, "application/json");
var post = await client.PostAsync(url, data);
This question already has answers here:
.NET HttpClient. How to POST string value?
(5 answers)
Closed 2 years ago.
Finaly figure out how to send QueryString as POST via HttpClient but another problem, URi string is too long becosue one of the string is file encoded to ToBase64String
Is posible to convert this solution:
NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
queryString.Add("mail_from", FromEmailAddress);
queryString.Add("mail_to", ToEmailAddress);
queryString.Add("mail_Attachment", ZipInBytes);
var response = await client.PostAsync($"/api?{queryString}", null);
Is there any other way how to send very long string? In postman working JSON raw data send to API
{
"mail_from":"value",
"mail_to":"value2,
"mail_Attachment":"very long string"
}
or I'm completely out and its not possible. My goal is send data with file from Outlook to API and save to database.
You should (if possible) send data such as files in the body, not the QueryString.
For instance:
//Class containing all POST data
public class PostBody{
public string FromEmailAddress{get;set;}
public string ToEmailAddress{get;set;}
public string ZipInBytes{get;set;}
}
// Populate model
PostBody body = new PostBody{ FromEmailAddress = FromEmailAddress, ToEmailAddress = ToEmailAddress, ZipInBytes = ZipInBytes};
// Serialize to JSON
var serializedBody = JsonConvert.SerializeObject(body);
// Set content type
client.Headers.Add("Content-Type", "application/json");
// Do request with serialized JSON as post body
var response = await client.PostAsync($"/api?{queryString}", serializedBody);
I am trying to prepare a JSON payload to a Post method. The server fails unable to parse my data. ToString() method on my values would not convert it to JSON correctly, can you please suggest a correct way of doing this.
var values = new Dictionary<string, string>
{
{
"type", "a"
}
, {
"card", "2"
}
};
var data = new StringContent(values.ToSttring(), Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
var response = client.PostAsync(myUrl, data).Result;
using (HttpContent content = response.content)
{
result = response.content.ReadAsStringAsync().Result;
}
You need to either manually serialize the object first using JsonConvert.SerializeObject
var values = new Dictionary<string, string>
{
{"type", "a"}, {"card", "2"}
};
var json = JsonConvert.SerializeObject(values);
var data = new StringContent(json, Encoding.UTF8, "application/json");
//...code removed for brevity
Or depending on your platform, use the PostAsJsonAsync extension method on HttpClient.
var values = new Dictionary<string, string>
{
{"type", "a"}, {"card", "2"}
};
var client = new HttpClient();
using(var response = client.PostAsJsonAsync(myUrl, values).Result) {
result = response.Content.ReadAsStringAsync().Result;
}
https://www.newtonsoft.com/json use this.
there are already a lot of similar topics.
Send JSON via POST in C# and Receive the JSON returned?
values.ToString() will not create a valid JSON formatted string.
I'd recommend you use a JSON parser, such as Json.Net or LitJson to convert your Dictionary into a valid json string. These libraries are capable of converting generic objects into valid JSON strings using reflection, and will be faster than manually serialising into the JSON format (although this is possible if required).
Please see here for the JSON string format definition (if you wish to manually serialise the objects), and for a list of 3rd party libraries at the bottom: http://www.json.org/
Using RestSharp 105.2.3
The API I am talking to requires use to send in a json body, but with a #c symbol as part of the field name. This is illegal in C# of course so I can't just use a dynamic object like below.
Is there a way to get the "#c" in the field name?
var client = new RestClient("https://aaa.bbb.com");
var request = new RestRequest(Method.POST);
request.AddJsonBody(new
{
#c=".Something",
username="johnsmith"
});
You could just use a string like this:
var client = new RestClient("https://aaa.bbb.com");
var request = new RestRequest(Method.POST);
string json = "{\"#c\":\".Something\", \"username\":\"johnsmith}";
request.AddJsonBody(json);
I am working in calling PHP API from c#. But, my problem arise when I have to pass associative array to API. I don't know exact implementation of PHP associative array in C# but I have used dictionary. It didn't works.
I have been using RestSharp to call API.
Code Implemenation:
var client = new RestClient(BaseUrl);
var request = new RestRequest(ResourceUrl, Method.POST);
IDictionary<string,string> dicRequeset = new Dictionary<string, string>
{
{"request-id", "1234"},
{"hardware-id", "CCCCXXX"},
};
request.AddParameter("request", dicRequeset);
var response = client.Execute(request);
var content = response.Content;
PHP API Implementation(Short):
* Expected input:
* string request[request-id,hardware-id]
* Return:
* code = 0 for success
* string activation_code
*/
function activate()
{
$license = $this->checkFetchLicense();
if (!$license instanceof License) return;
$response = $license->activate((array)$this->_request->getParam('request'));
}
Can someone help me to pass array to PHP API from C#?
Maybe adding the pairs makes differences in conventions in C# and PHP? Have you tried using Add?
IDictionary<string,string> dicRequeset = new Dictionary<string, string>();
dicRequeset.Add("request-id", "1234");
dicRequeset.Add("hardware-id", "CCCCXXX");
Or using indexer?
dicRequeset["request-id"] = "1234";
dicRequeset["hardware-id"] = "CCCXXX";
Or the best I can imagine is JSON as it is designed for the purpose of transmission.
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new {request-id = "1234", hardware-id = "CCCXXX"});
The problem in the third variant despite I marked it as the best, might be that the PHP API may not decode the JSON string, because it might not be designed that way. But in general purpose JSON is meant to solve that kind of problems.
Though late post but I've solved this problem by using following approach :
var request = new RestRequest(ResourceUrl, Method.POST);
request.AddParameter("request[request-id]", hardwareId);
request.AddParameter("request[hardware-id]", hardwareId);
if I guess right, the AddParameter method of RestSharp doesn't automatically serialize an object to json thus insteadly just calls the object's toString method.
So try to get a JSON.net library and make the json encoding manually,
IDictionary<string,string> dicRequeset = new Dictionary<string, string>
{
{"request-id", "1234"},
{"hardware-id", "CCCCXXX"},
};
var jsonstr = JsonConvert.SerializeObject(dicRequeset);
request.AddParameter("request", jsonstr);
this should work.