json call with C# [duplicate] - c#

This question already has answers here:
How to post JSON to a server using C#?
(15 answers)
Closed 1 year ago.
I am trying to make a json call using C#. I made a stab at creating a call, but it did not work:
public bool SendAnSMSMessage(string message)
{
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://api.pennysms.com/jsonrpc");
request.Method = "POST";
request.ContentType = "application/json";
string json = "{ \"method\": \"send\", "+
" \"params\": [ "+
" \"IPutAGuidHere\", "+
" \"msg#MyCompany.com\", "+
" \"MyTenDigitNumberWasHere\", "+
" \""+message+"\" " +
" ] "+
"}";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
return true;
}
Any advice on how to make this work would be appreciated.

In your code you don't get the HttpResponse, so you won't see what the server side sends you back.
you need to get the Response similar to the way you get (make) the Request. So
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"method\": \"send\", " +
" \"params\": [ " +
" \"IPutAGuidHere\", " +
" \"msg#MyCompany.com\", " +
" \"MyTenDigitNumberWasHere\", " +
" \"" + message + "\" " +
" ] " +
"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
I also notice in the pennysms documentation that they expect a content type of "text/json" and not "application/json". That may not make a difference, but it's worth trying in case it doesn't work.

just continuing what #Mulki made with his code
public string WebRequestinJson(string url, string postData)
{
string ret = string.Empty;
StreamWriter requestWriter;
var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(postData);
}
}
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
Stream resStream = resp.GetResponseStream();
StreamReader reader = new StreamReader(resStream);
ret = reader.ReadToEnd();
return ret;
}

Here's a variation of Shiv Kumar's answer, using Newtonsoft.Json (aka Json.NET):
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var serializer = new Newtonsoft.Json.JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
{
serializer.Serialize(tw,
new {method= "send",
#params = new string[]{
"IPutAGuidHere",
"msg#MyCompany.com",
"MyTenDigitNumberWasHere",
message
}});
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}

If your function resides in an mvc controller u can use the below code with a dictionary object of what you want to convert to json
Json(someDictionaryObj, JsonRequestBehavior.AllowGet);
Also try and look at system.web.script.serialization.javascriptserializer if you are using .net 3.5
as for your web request...it seems ok at first glance..
I would use something like this..
public void WebRequestinJson(string url, string postData)
{
StreamWriter requestWriter;
var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
//POST the data.
using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter.Write(postData);
}
}
}
May be you can make the post and json string a parameter and use this as a generic webrequest method for all calls.

Its just a sample of how to post Json data and get Json data to/from a Rest API in BIDS 2008 using System.Net.WebRequest and without using newtonsoft. This is just a sample code and definitely can be fine tuned (well tested and it works and serves my test purpose like a charm). Its just to give you an Idea. I wanted this thread but couldn't find hence posting this.These were my major sources from where I pulled this.
Link 1 and Link 2
Code that works(unit tested)
//Get Example
var httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
var username = "usernameForYourApi";
var password = "passwordForYourApi";
var bytes = Encoding.UTF8.GetBytes(username + ":" + password);
httpWebRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
var httpResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
Dts.Events.FireInformation(3, "result from readng stream", result, "", 0, ref fireagain);
}
//Post Example
var httpWebRequestPost = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://abc.def.org/testAPI/api/TestFile");
httpWebRequestPost.ContentType = "application/json";
httpWebRequestPost.Method = "POST";
bytes = Encoding.UTF8.GetBytes(username + ":" + password);
httpWebRequestPost.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
//POST DATA newtonsoft didnt worked with BIDS 2008 in this test package
//json https://stackoverflow.com/questions/6201529/how-do-i-turn-a-c-sharp-object-into-a-json-string-in-net
// fill File model with some test data
CSharpComplexClass fileModel = new CSharpComplexClass();
fileModel.CarrierID = 2;
fileModel.InvoiceFileDate = DateTime.Now;
fileModel.EntryMethodID = EntryMethod.Manual;
fileModel.InvoiceFileStatusID = FileStatus.NeedsReview;
fileModel.CreateUserID = "37f18f01-da45-4d7c-a586-97a0277440ef";
string json = new JavaScriptSerializer().Serialize(fileModel);
Dts.Events.FireInformation(3, "reached json", json, "", 0, ref fireagain);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
httpWebRequestPost.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = httpWebRequestPost.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = httpWebRequestPost.GetResponse();
// Display the status.
//Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Dts.Events.FireInformation(3, "Display the status", ((HttpWebResponse)response).StatusDescription, "", 0, ref fireagain);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
Dts.Events.FireInformation(3, "responseFromServer ", responseFromServer, "", 0, ref fireagain);
References in my test script task inside BIDS 2008(having SP1 and 3.5 framework)

Related

Issue while retrieving the data from elastic using c#

I am trying to retrieve the data from elastic DB by using multiple conditions like, "cu_ticketLastUpdated_date" in between 24hrs and "platform" which belongs to COSMOS. I am using the below code for these conditions
{
"from": 0,
"size": 10000,
"query": {
"bool": {
"must": [
{"match": {
"platform": "COSMOS"
}}],
"filter": [
{"range": {
"cu_ticketLastUpdated_date": {
"gte": "2022-05-31 00:00:00",
"lt": "2022-05-31 23:59:59"
}}}]}}}
The above code is working fine when I have used it in Postman.(satisfying both "cu_ticketLastUpdated_date" and "platform" conditions)
But if I am trying to implement the same conditions in C# only one condition is satisfying i.e.; "cu_ticketLastUpdated_date" in between 24hrs rest condition "platform" = COSMOS is not working.... Instead of that my C# code is retrieving all Platforms data in between 24hrs
Below is my c# code. In string json I am passing these conditions.
public static string COSMOS(string getAPiurl, string ApiUserId, string ApiPassword)
{
string url = getAPiurl;
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "POST";
webrequest.ContentType = "application/JSON";
webrequest.Accept = "application/JSON";
String username = ApiUserId;
String password = ApiPassword;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
webrequest.Headers.Add("Authorization", "Basic " + encoded);
using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
{
string json = "{\"from\": 0,\"size\": 10000,\"query\":{\"bool\":{\"should\":[{\"match\":{\"platform\":{\"query\":\"COSMOS\"}}}],\"filter\":[{\"range\":{\"cu_ticketLastUpdated_date\":{\"gte\":\"2022-05-31 00:00:00\",\"lt\":\"2022-05-31 23:59:59\"}}}]}}}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)webrequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
httpResponse.Close();
//MessageBox.Show(result);
return result;
}
}
I am trying multiple ways to fix it. But I am unable to fix this issue. Can any one help me with the solution.
Tldr;
You are not doing the same query in postman and in c#.
In postman you use a must clause while in the c# you use should.
To Fix
public static string COSMOS(string getAPiurl, string ApiUserId, string ApiPassword)
{
string url = getAPiurl;
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.Method = "POST";
webrequest.ContentType = "application/JSON";
webrequest.Accept = "application/JSON";
String username = ApiUserId;
String password = ApiPassword;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
webrequest.Headers.Add("Authorization", "Basic " + encoded);
using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
{
string json = "{\"from\": 0,\"size\": 10000,\"query\":{\"bool\":{\"must\":[{\"match\":{\"platform\":{\"query\":\"COSMOS\"}}}],\"filter\":[{\"range\":{\"cu_ticketLastUpdated_date\":{\"gte\":\"2022-05-31 00:00:00\",\"lt\":\"2022-05-31 23:59:59\"}}}]}}}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)webrequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
httpResponse.Close();
//MessageBox.Show(result);
return result;
}
}

Postmates API not working

I am using postmates Delivery Quote API for the last one year, And it is working good by the time when I checked.
But now it seems to be not working
It is throwing an exception with an HTML text with some enable cookies and captcha
I can't understand if i am missing some updates from postmates
Here is my coding
HttpWebRequest req = WebRequest.Create(new Uri("https://api.postmates.com/v1/customers/" + PostmatesCustomerId + "/delivery_quotes")) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.Headers.Add("Authorization", "Basic " + Base64string);
StringBuilder paramz = new StringBuilder();
paramz.Append("pickup_address=" + PickUpAddress + "&dropoff_address=" + DeliveryAddress);
byte[] formData =
UTF8Encoding.UTF8.GetBytes(paramz.ToString());
req.ContentLength = formData.Length;
// Send the request:
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}
string responseString = null;
using (HttpWebResponse resp = req.GetResponse()
as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
responseString = reader.ReadToEnd();
}
If you're outside of the US, try using a VPN as a workaround to test.

How to call an MVC action from a console app with no View

I am trying to post a string value to a method within a controller. My controller has no views. Is it possible to call and post this action method from a console application?
I have tried a few solution from stack overflow.
code in console app:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:6586/MacCommService/LoadBalanceMacValues");
webRequest.Method = "POST";
var data = string.Format("jsonValues={0}", Uri.EscapeDataString(encryptedJson));
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(data);
requestWriter.Close();
code in MacCommServiceController:
public ActionResult LoadBalanceMacValues(string jsonValues) {
//var macKey = ConfigurationManager.AppSettings["macKey"].ToString();
jsonValues = "etc";
Response.Write("Json from action: " + jsonValues);
return View();
}
I gess you don't set ContentType of your httpWebRequest and don't format your Json well:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:6586/MacCommService/LoadBalanceMacValues");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"jsonValues\" : \"" + Uri.EscapeDataString(encryptedJson) + "\" }";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Also in your controller you should return Json like this:
public JsonResult LoadBalanceMacValues(string jsonValues) {
jsonValues = "etc";
return Json("Json from action: " + jsonValues);
}

Posting tasks to Asana using API in C#

I'm trying to figure out how to post a new task to a user in asana, but I keep getting the 400 error code. Can anyone tell me what I am doing wrong.
This is what I have so far:
string apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string ID = "xxxxxxxxxxxxx";
string url = #"https://app.asana.com/api/1.0/tasks";
Data dat = new Data();
dat.workspace = ID;
dat.name = "Buy eggs";
dat.notes = "Testing";
string json = JsonConvert.SerializeObject(dat);
string data ="\"data\": " + json;
byte[] bytes = Encoding.UTF8.GetBytes(data);
var req = (HttpWebRequest)WebRequest.Create(url);
Console.WriteLine(bytes.ToString());
req.Method = WebRequestMethods.Http.Post;
req.ContentLength = bytes.Length;
req.ContentType = "application/json";
var authInfo = apiKey + ":";
var encodedAuthInfo = Convert.ToBase64String(
Encoding.Default.GetBytes(authInfo));
req.Headers.Add("Authorization", "Basic " + encodedAuthInfo);
req.ContentLength = bytes.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
try
{
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string res = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(res);
Console.ReadLine();
}
catch (WebException ex)
{
HttpWebResponse response = ((HttpWebResponse)ex.Response);
string e = url + " caused a " + (int)response.StatusCode + " error.\n" + response.StatusDescription;
Console.WriteLine(e);
Console.ReadLine();
}
I put the serial converter, did i do it wrong?
As the first comment points out, you need to serialize the data properly. The final body posted should look something like:
{ "data": { "name": "My Example Task", ... }}
(Except of course with the ... replaced with more fields.)
I have researched a long and found below code useful and working. I can successfully post Task to Asana through my application. I have used Json serializer for dot net. Thanks to Newtonsoft.Json.
string json = null;
byte[] bytes = null;
string url = "https://app.asana.com/api/1.0/tasks";
HttpWebRequest req = default(HttpWebRequest);
Stream reqStream = default(Stream);
string authInfo = null;
Task TaskData = new Task();
try
{
authInfo = apiKey + Convert.ToString(":");
TaskData.workspace = WorkspaceId;
TaskData.name = TaskName;
TaskData.notes = TaskNotes;
json = JsonConvert.SerializeObject(TaskData);
json = json.Insert((json.Length - 1), ",\"projects\":[" + ProjectId + "]");
json = Convert.ToString("{ \"data\":") + json + "}";
bytes = Encoding.UTF8.GetBytes(json);
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = WebRequestMethods.Http.Post;
req.ContentType = "application/json";
req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)));
req.ContentLength = bytes.Length;
reqStream = req.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string res = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(res);
Console.ReadLine();
string finalString = res.Remove(0, 8);
finalString = finalString.Remove((finalString.Length - 1));
AsanaObjectId newtask = JsonConvert.DeserializeObject<AsanaObjectId>(finalString);
return newtask;
}
catch (WebException ex)
{
HttpWebResponse response = (HttpWebResponse)ex.Response;
string resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
MessageBox.Show(resp);
System.Environment.Exit(0);
}

WebDAV get free space info

I'm working with Yandex Disk API (http://api.yandex.com/disk/doc/dg/reference/propfind_space-request.xml).
Having trouble with adding property in the request body (quota-available-bytes and quota-used-bytes)
public static string SpaceInfo(string path)
{
// Authorization.
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create("https://webdav.yandex.ru/");
webReq.Accept = "*/*";
webReq.Headers.Add("Depth: 0");
webReq.Headers.Add("Authorization: OAuth " + token);
webReq.Method = "PROPFIND";
// Adding data in body request.
string inputData = #"<D:propfind xmlns:D=""DAV:""><D:prop><quota-available-bytes/></D:prop></D:propfind>";
byte[] buffer = new ASCIIEncoding().GetBytes(inputData);
webReq.ContentType = "text/xml; encoding='utf-8";
webReq.ContentLength = buffer.Length;
try
{
HttpWebResponse resp = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string dinfo = sr.ReadToEnd();
return dinfo;
}
}
I don't get any response, maybe i can use another method? What should i do?
Thanks!
quota-available-bytes should use same namespace "D"

Categories