I'm new to C# and I'm trying to get the JSON response from a REST request using RestSharp;
The request I want to execute is the following one : "http://myurl.com/api/getCatalog?token=saga001". It works great if I'm executing it in a browser.
I've tried this :
var client = new RestClient("http://myurl.com/api/");
var request = new RestRequest("getCatalog?token=saga001");
var queryResult = client.Execute(request);
Console.WriteLine(queryResult);
And I get "RestSharp.RestReponse" instead of the JSON result I'm hopping for.
Thanks for your help !
Try:
var client = new RestClient("http://myurl.com/api/");
var request = new RestRequest("getCatalog?token={token}", Method.GET);
request.AddParameter("token", "saga001", ParameterType.UrlSegment);
// request.AddUrlSegment("token", "saga001");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
This is old but I was just struggling with this too. This is the easiest way I found.
var client = new RestClient("http://myurl.com/api/");
var request = new RestRequest("getCatalog?token=saga001");
var response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
// Two ways to get the result:
string rawResponse = response.Content;
MyClass myClass = new JsonDeserializer().Deserialize<MyClass>(response);
}
Try as below:
var client = new RestClient("http://myurl.com/api/");
client.ClearHandlers();
var jsonDeserializer = new JsonDeserializer();
client.AddHandler("application/json", jsonDeserializer);
var request = new RestRequest("getCatalog?token=saga001");
var queryResult = client.Execute(request);
Console.WriteLine(queryResult);
If you want to save the result into JSON file:
You should use these namespaces:
using RestSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
var client = new RestClient("http://myurl.com/api/");
var request = new RestRequest(Method.GET);
request.AddHeader("content-type", "application/json");
var queryResult = client.Execute<Object>(request).Data;
string json = JsonConvert.SerializeObject(queryResult);
System.IO.File.WriteAllText(#"C:\...\path.json", json);
Related
I'm trying to send a http post request in JSON format which should look like this:
{
"id":"72832",
"name":"John"
}
I have attempted to do it like below but if I am correct this is not sending a request in json format.
var values = new Dictionary<string,string>
{
{"id","72832"},
{"name","John"}
};
using (HttpClient client = new HttpClient())
{
var content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await client.PostAsync("https://myurl",content);
// code to do something with response
}
How could I modify the code to send the request in json format?
try this
using (var client = new HttpClient())
{
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
var baseAddress = "https://....";
var api = "/controller/action";
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Add(contentType);
var data = new Dictionary<string,string>
{
{"id","72832"},
{"name","John"}
};
var jsonData = JsonConvert.SerializeObject(data);
var contentData = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = await client.PostAsync(api, contentData);
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<object>(stringData);
}
}
Update
If the request comes back with Json data in the form `
{ "return":"8.00", "name":"John" }
you have to create result model
public class ResultModel
{
public string Name {get; set;}
public double Return {get; set;}
}
and code will be
if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<ResultModel>(stringData);
var value=result.Return;
var name=Result.Name;
}
I would start off by using RestSharp.
dotnet add package RestSharp
Then you can send requests like this:
public async Task<IRestResult> PostAsync(string url, object body)
{
var client = new RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.Post);
request.AddJsonBody(body);
var response = await client.ExecuteAsync(request);
return response;
}
Just pass in your dictionary as the body object - I would recommend creating a DTOS class to send through though.
Then you can get certain aspects of the RestResponse object that is returned like:
var returnContent = response.Content;
var statusCode = response.StatusCode;
I had a problem to process soapEnvelopeXml document using PostAsync method from IHttpClientFactory.
This is what I was trying to do :
var soapEnvelopeXml = ObjectToXMLDocumentConverter.ObjectAsXmlDocument(object);
var content = new StringContent(soapEnvelopeXml.ToString(), Encoding.UTF8, "text/xml");
var response = await client.PostAsync(endpoint, content);
This was producing 400 Bad Request error.
What I find as a solution to my problem is direct usage of SOAP string instead of first converting it to XML message :
var soapString = ObjectToSoapRequestConverter.ObjectSoapStringRequest(object);
using (var client = clientFactory.CreateClient())
{
client.DefaultRequestHeaders.Add(...);
client.DefaultRequestHeaders.Add(...);
var content = new StringContent(soapString, Encoding.UTF8, "text/xml");
using (var response = await client.PostAsync(endpoint, content))
{
var soapResponse = await response.Content.ReadAsStringAsync();
...
}
}
I am trying to update a field of a work-item on TFS using the TFS API according to the Microsoft document. There is something wrong with the api "Update work items" when using the sample code listed on the page, the returning status code of the response is 400. No matter what I did, the status code is always 400, can anyone please give me some help?
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
public void UpdateWorkItemUpdateField()
{
string _personalAccessToken = "xxxxxxxxxxxxxx";
string _credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", _personalAccessToken)));
string _id = "111";
Object[] patchDocument = new Object[3];
patchDocument[0] = new { op = "test", path = "/rev", value = "1" };
patchDocument[1] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", value = "2" };
patchDocument[2] = new { op = "add", path = "/fields/System.History", value = "Changing priority" };
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _credentials);
var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json"); // mediaType needs to be application/json-patch+json for a patch call
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, "https://accountname.visualstudio.com/_apis/wit/workitems/" + _id + "?api-version=2.2") { Content = patchValue };
var response = client.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
}
}
}
You are using a wrong mediaType, it should be 'application/json-patch+json' not 'application/json'.
var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json");
In the code sample, it has already noted you:
// mediaType needs to be application/json-patch+json for a patch call
You're invoke a Patch call, so please change the mediaType to application/json-patch+json.
I'm trying to upload a transient document file to Adobe Sign in C#, and it has driven me to my wits end trying to get it to work.
I've even contacted Adobe, and even they don't know how to do it.
My code is as follows:
if (!File.Exists(#"documents\1-Registration Form.pdf"))
{
return;
}
Models objGetData = new Models();
RestClient objClient = new RestClient("https://api.na1.echosign.com:443/api/rest/v5");
RestRequest objRequest = new RestRequest("transientDocuments", Method.POST);
objRequest.AddFile("file", File.ReadAllBytes(#"documents\1-Registration Form.pdf"), "1-Registration Form.pdf");
objRequest.AddHeader("Access-Token", "-My Token Here-");
objRequest.RequestFormat = DataFormat.Json;
IRestResponse objResponse = objClient.Execute(objRequest);
var content = objResponse.Content;
JObject jsonLinq = JObject.Parse(content);
try
{
var objResultObjects = AllData(jsonLinq).First(c => c.Type == JTokenType.Array && c.Path.Contains("libraryDocumentList")).Children<JObject>();
}
catch(Exception ex)
{
ex.LogExceptionToDatabase();
}
return;
Here's the response that I'm getting as the result of my most recent attempt:
"{\"code\":\"NOT_FOUND\",\"message\":\"Resource not found\"}"
I typically get Bad request saying the file isn't present or a not found error, but they're not always the same.
All help will be appreciated.
EDIT:
The following code will give a response with a list of library docs so I know it's not the URL.
var objGetData = new Models();
var objClient = new RestClient("https://api.na1.echosign.com:443/api/rest/v5");
var objRequest = new RestRequest("libraryDocuments", Method.GET);
objRequest.AddHeader("Access-Token", "- My Key -");
objRequest.RequestFormat = DataFormat.Json;
objRequest.AddBody(objGetData);
IRestResponse objResponse = objClient.Execute(objRequest);
var content = objResponse.Content;
JObject jsonLinq = JObject.Parse(content);
SOLUTION:
var objClient = new RestClient(#"https://api.na1.echosign.com:443/api/rest/v5/");
var objRequest = new RestRequest(#"transientDocuments", Method.POST);
var thisFile = File.ReadAllBytes( #"documents\1-Registration Form.pdf");
objRequest.AddFile("File", File.ReadAllBytes( #"documents\1-Registration Form.pdf"), "1-Registration Form.pdf");
objRequest.AddHeader("Access-Token", "-MyToken-");
objRequest.RequestFormat = DataFormat.Json;
IRestResponse objResponse = objClient.Execute(objRequest);
var content = objResponse.Content;
JObject jsonLinq = JObject.Parse(content);
This did it. Apparently "file" is bad but "File" is okay.
var objClient = new RestClient(#"https://api.na1.echosign.com:443/api/rest/v5/");
var objRequest = new RestRequest(#"transientDocuments", Method.POST);
var thisFile = File.ReadAllBytes( #"documents\1-Registration Form.pdf");
objRequest.AddFile("File", File.ReadAllBytes( #"documents\1-Registration Form.pdf"), "1-Registration Form.pdf");
objRequest.AddHeader("Access-Token", "-MyToken-");
objRequest.RequestFormat = DataFormat.Json;
IRestResponse objResponse = objClient.Execute(objRequest);
var content = objResponse.Content;
JObject jsonLinq = JObject.Parse(content);
Not sure if the URI is correct, check missing '/' on the end of the RestClient (shouldn't be needed but still).
Lastly if you browse to the location in Angular 1 does it give you the same issue? I ask as this is a lot lighter to test and you can see using F12 developer tools exactly what is coming back from the open https channel.
The below code is for api call using restclient...But it is not getting response any one have idea about this?
var client = new RestClient("http://www.sentiment140.com");
var request = new RestRequest(Method.POST);
request.Resource = "api/bulkClassifyJson";
request.AddParameter("appid", "abcd#gmail.com");
request.RequestFormat = DataFormat.Json;
request.AddBody(text);
var response = client.Execute(request);
var serializer = new JavaScriptSerializer();
List<Sentimental> items = serializer.Deserialize<List<Sentimental>>(response.Content);
return items;