I need to read a value from HTTP response. Here is an example of the response in which I'm trying to fetch (description) value:
{
"result":{
"code":"200.300.404",
"description":"successful"
},
"buildNumber":"1f9#2021-12-23 09:56:49 +0000",
"timestamp":"2021-12-25 17:22:35+0000",
"ndc":"8976eaedf8da"
}
Here is my code
Dictionary<string, dynamic> responseData;
string data = "entityId=8a8294174d0595bb014d05d82e5b01d2";
string url = "https://test.oppwa.com/v1/checkouts/" + CheckoutId + "/payment?" + data;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
request.Headers["Authorization"] = "Bearer xxxx";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
// var s = new JavaScriptSerializer();
responseData = JsonSerializer.Deserialize<Dictionary<string, dynamic>>(reader.ReadToEnd());
reader.Close();
dataStream.Close();
}
// If responseDate.Description=success then enroll user and register the payment
var res = responseData["result"];
// I'm trying to do this but not working
var res = responseData["result"]["description"];
return responseData;
Any help is appreciated
Thanks
You can use JToken or JObject of Newtonsoft.Json.Linq.
For example, if your response format like as below:
{
"result":{
"code":"200.300.404",
"description":"successful"
},
"buildNumber":"1f9#2021-12-23 09:56:49 +0000",
"timestamp":"2021-12-25 17:22:35+0000",
"ndc":"8976eaedf8da"
}
You can use below code for this purpose:
...
string webResponseAsString = reader.ReadToEnd();
dynamic dynamicResult = JToken.Parse(webResponseAsString);
string description = dynamicResult.result.description
For more details, you can visit this links:
Using JSON.NET for dynamic JSON parsing
Querying JSON with dynamic
What is better to use when parsing dynamic JSON data: JToken or c# built in dynamic type
try this
StreamReader reader = new StreamReader(dataStream);
var json = reader.ReadToEnd();
...
var jsonObject=JObject.Parse(json);
var result=jsonObject["result"];
var description = jsonObject["result"]["description"];
// or
var description =result["description"];
description value
successful
responseData["result"].description
Will get you the JValue of "successful".
Although there are some other issues. Deserialize needs an instance of JsonSerializer, it is not a static method. Here is a full example without using a Dictionary.
var response = #"
{
""result"":{
""code"":""200.300.404"",
""description"":""successful""
},
""buildNumber"":""1f9#2021-12-23 09:56:49 +0000"",
""timestamp"":""2021-12-25 17:22:35+0000"",
""ndc"":""8976eaedf8da""
}
";
var responseData = new JsonSerializer()
.Deserialize<dynamic>(
new JsonTextReader(new StringReader(response)));
responseData.result.description; //successful
Related
This question already has answers here:
How to post JSON to a server using C#?
(15 answers)
Closed 1 year ago.
i, tried putting body in request but didn't actually worked,
in body i want to put which is in json format {"ClaimNo":"123123"}
i have used this as code:
string ClaimStatus_url = "https:xyz";
WebRequest request = WebRequest.Create(ClaimStatus_url);
request.ContentType = "application/json";
request.Method = "POST";
//request.Headers = "";// i used this for puting body in it but did not work
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string result = reader.ReadToEnd();
using System.Text;
using System.Text.Json;
namespace TestPostData;
public class Data
{
public int ClaimNo { get; set; }
}
public static class Program
{
public static void Main()
{
var postData = new Data
{
ClaimNo = 123123,
};
var client = new System.Net.Http.HttpClient();
var content = new StringContent(JsonSerializer.Serialize(postData), Encoding.UTF8, "application/json");
var response = client.PostAsync("https:xyz", content).Result;
}
}
That is an example of using HttpClient class that is now recommended to use instead WebRequest.
Try this, i hope it will work.
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
I would start off by using RestSharp.
dotnet add package RestSharp
Then I would create a DTOS object with the contents that you want to send in the json:
public class DtosObject
{
public string ClaimNo {get; set;}
}
Then pass that in as the object (I would call the class something relevant to the data it contains). If you only are using ClaimNo you could also use a KeyValuePair like this:
var body = new KeyValuePair<string, string>("ClaimNo", "123123");
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;
}
string ClaimStatus_url = "https://qms.xyz.in/FGClaimWsAPI/api/Common/FetchClaimdetails";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(ClaimStatus_url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"ClaimNo\":\""+ userProfile.ClaimNumber +"\"}";
//string json = "{\"ClaimNo\":\"CV010831\"}";
//await turnContext.SendActivityAsync(MessageFactory.Text(json, json), cancellationToken);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var result1 = "" ;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
result1 = result.Substring(1, result.Length -2); // to bring response result in proper format
}
_claimstaus = GenrateJSON_Claim(result1);
This upper code worked
Here is my code below. Getting the token from shopify works fine. However while creating a new product it keeps giving me an error. I've tried everything possible and it still does not work. Any advice would be appreciated.
Here's how I call the CreateNewProduct method passing the access token from shopify and the shopname with the products endpoint.
CreateNewProduct(accessTokenDTO.access_token, "https://{myshopname}.myshopify.com/admin/api/2020-10/products.json");
Here's the method below.
public static void CreateNewProduct(string token, string Url)
{
Uri shopUri = new Uri(Url);
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(shopUri);
GETRequest.ContentType = "application/json";
GETRequest.Headers.Add("X-Shopify-Access-Token", token);
GETRequest.PreAuthenticate = true;
GETRequest.Method = "PUT";
using (var streamWriter = new StreamWriter(GETRequest.GetRequestStream()))
{
string json = "{\"product\": { \"title\": \"Burton Custom Freestyle 151\", \"body_html\": \"<strong>Good snowboard!</strong>\", \"vendor\": \"Burton\", \"product_type\": \"Snowboard\", \"tags\": [ \"Barnes & Noble\", \"John's Fav\", \"\\Big Air\\]}";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(GETResponse.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
Debug.WriteLine("Response Text: " + responseText);
}
GETResponse.Close();
}
400 BadRequest normally refers to the body you are sending with your request is not valid according to the api.
Wheni look at your string that is supposed to be a json, it shows invalid data at the end.
[ \"Barnes & Noble\", \"John's Fav\", \"\\Big Air\\]}";
You are missing closing quotes after Big Air. Also, not sure if those backslash are supposed to be there around Big Air but definitely the missing closing quotes would seem to be the issue
There was an issue with the json not being formatted correctly and method was a PUT instead of POST. See working code below.
public static void CreateNewProduct(string token, string Url)
{
Uri shopUri = new Uri(Url);
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(shopUri);
GETRequest.ContentType = "application/json";
GETRequest.Headers.Add("X-Shopify-Access-Token", token);
GETRequest.PreAuthenticate = true;
GETRequest.Method = "POST";
using (var streamWriter = new StreamWriter(GETRequest.GetRequestStream()))
{
string json = "{\"product\": { \"title\": \"Burton Custom Freestyle 151\", \"body_html\": \"<strong>Good snowboard!</strong>\", \"vendor\": \"Burton\", \"product_type\": \"Snowboard\"} }";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(GETResponse.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
Debug.WriteLine("Response Text: " + responseText);
}
GETResponse.Close();
}
Fail to detect the language of the content input.
I've double checked the API key and it's correct.
When I try to detect the language, it appears error 401.
// ***** DETECT LANGUAGE OF TEXT TO BE TRANSLATED
private string DetectLanguage(string text)
{
string uri = TEXT_ANALYTICS_API_ENDPOINT + "languages?numberOfLanguagesToDetect=1";
// create request to Text Analytics API
HttpWebRequest detectLanguageWebRequest = (HttpWebRequest)WebRequest.Create(uri);
detectLanguageWebRequest.Headers.Add("Ocp-Apim-Subscription-Key", TEXT_ANALYTICS_API_SUBSCRIPTION_KEY);
detectLanguageWebRequest.Method = "POST";
// create and send body of request
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonText = serializer.Serialize(text);
string body = "{ \"documents\": [ { \"id\": \"0\", \"text\": " + jsonText + "} ] }";
byte[] data = Encoding.UTF8.GetBytes(body);
detectLanguageWebRequest.ContentLength = data.Length;
using (var requestStream = detectLanguageWebRequest.GetRequestStream())
requestStream.Write(data, 0, data.Length);
HttpWebResponse response = (HttpWebResponse)detectLanguageWebRequest.GetResponse();
// read and parse JSON response
var responseStream = response.GetResponseStream();
var jsonString = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")).ReadToEnd();
dynamic jsonResponse = serializer.DeserializeObject(jsonString);
// fish out the detected language code
var languageInfo = jsonResponse["documents"][0]["detectedLanguages"][0];
if (languageInfo["score"] > (decimal)0.5)
return languageInfo["iso6391Name"];
else
return "";
}
I mean, this is piece of my code:
// Create the web request (posts/1)
HttpWebRequest request = WebRequest.Create("https://jsonplaceholder.typicode.com/posts/1") as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
{
string myString = reader.ReadToEnd();
System.IO.File.WriteAllText(#"C:\Users\admin\Documents\Visual Studio 2015\Projects\WriteText.json", myString);
}
// JSON deserialize from a file
String JSONstring = File.ReadAllText(#"C:\Users\admin\Documents\Visual Studio 2015\Projects\WriteText.json");
// List<PARSE> pList = JsonConvert.DeserializeObject<List<PARSE>>(JSONstring);
PARSE pList = JsonConvert.DeserializeObject<PARSE>(JSONstring);
How can I do this thing without saving the stream and again loading it to a string. I want use my stream directly to a String 'JSONstring' and then parse it.
Your code contains solution
// Create the web request (posts/1)
HttpWebRequest request = WebRequest.Create("https://jsonplaceholder.typicode.com/posts/1") as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
{
//string myString = reader.ReadToEnd();
//System.IO.File.WriteAllText(#"C:\Users\admin\Documents\Visual Studio 2015\Projects\WriteText.json", myString);
}
// JSON deserialize from a file
// String JSONstring = File.ReadAllText(#"C:\Users\admin\Documents\Visual Studio 2015\Projects\WriteText.json");
// List<PARSE> pList = JsonConvert.DeserializeObject<List<PARSE>>(JSONstring);
PARSE pList = JsonConvert.DeserializeObject<PARSE>(reader.ReadToEnd());
reader.close();
Here's an example of how to parse an HTTP stream into a Json (with no error handling). Play with it and let us know if you run into anything specific. In this code. API_Json is the class with the deserialized classes, and I am deserializing API_Json.RootObject:
public async Task<API_Json.RootObject> walMart_Lookup(string url)
{
lookupIsWorking = true;
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using (HttpClient http = new HttpClient(handler))
{
http.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
http.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
url = String.Format(url);
using (var response = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
Console.WriteLine(response);
var serializer = new JsonSerializer();
using (StreamReader sr = new StreamReader(await response.Content.ReadAsStreamAsync()))
{
using (var jsonTextReader = new JsonTextReader(sr))
{
var root = serializer.Deserialize<API_Json.RootObject>(jsonTextReader);
lookupIsWorking = false;
return root;
}
}
//var obj = (API_Json_Special_Feeds.RootObject)serializer.Deserialize(sr, typeof(API_Json_Special_Feeds.RootObject));
//return obj;
}
}
}
Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
if (data["ReturnValue"].Equals("0"))
{
List<M_Ninushi> m_ninushis = new M_NINUSHI_DAO().GetList(data["LastUpdateDate"]);
string data_m_ninushi = JsonConvert.SerializeObject(m_ninushis);
string sentResponse = Util.FilterData(data_m_ninushi);
Dictionary<string, string> dataResponse = JsonConvert.DeserializeObject<Dictionary<string, string>>(sentResponse);
if (dataResponse["ReturnValue"].Equals("0"))
{
return 0;
}
else
{
return 1;
}
}
this id my code in webservice use asp.net. I use HttpWebRequest send data to symfony2 api
FilterData
XElement xdoc = XElement.Load(configFileName);
var objStringConnection = xdoc.Descendants("URL").Select(e => new { filter_data = e.Descendants("URL_FILTER_DATA").FirstOrDefault().Value }).SingleOrDefault();
string urlAddress = objStringConnection.filter_data;
System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return true; };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
Dictionary<string, string> json = new Dictionary<string, string>();
json.Add("M_Ninushi", data);
byte[] dataSent = Encoding.ASCII.GetBytes(json.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//application/x-www-form-urlencoded
request.ContentLength = dataSent.Length;
Stream writer = request.GetRequestStream();
writer.Write(dataSent, 0, dataSent.Length);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
string dataResponse = readStream.ReadToEnd();
response.Close();
readStream.Close();
return dataResponse;
}
this id my code in webservice use asp.net. I use HttpWebRequest send data to symfony2 api
I know how to send data but I don't know how to get data in symfony2 . someone help me
C# Code Corrections
First, we need to correct the Content-Type sent to the server hosting the Symfony2 application. The data you are sending is not in the proper format for application/x-www-form-urlencoded. Change it to application/json.
Also, JSON data MUST be encoded in Unicode. In PHP, json_decode() only supports UTF-8 encoded strings. Therefore you must use Encoding.UTF8.GetBytes instead of Encoding.ASCII.GetBytes.
Dictionary.toString() does not return a JSON string. Use Json.NET.
Receiving JSON Data in Symfony2
In your Controller, you can use Symfony\Component\HttpFoundation\Request::getContent() to retrieve the form content.
<?php
namespace Company\CodeExampleBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\HttpException;
class RestAPIController extends Controller
{
public function doSomethingInterestingAction(Request $request)
{
if($request->headers->get('Content-Type') !== 'application/json') {
throw $this->createBadRequestException();
}
$jsonData = json_decode($request->getContent(), true);
if($jsonData === null) {
throw $this->createBadRequestException();
}
// DO SOMETHING WITH $jsonData
}
protected function createBadRequestException()
{
return new HttpException(400, 'This endpoint expects JSON data in the POST body and requires Content-Type to be set to application/json.');
}
}