I have the following GET request:
string url = #"http://api.flexianalysis.com/services/flexianalysisservice.svc/TechnicalAnalysisByCategory?clientid=___&category=forex&key=____";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
rawJson = new StreamReader(response.GetResponseStream()).ReadToEnd();
//html = reader.ReadToEnd();
}
This is an example of the JSON:
[{"ID":133739,"TickerID":23,"CategoryID":3,"ClientID":5044,"TickerDateTime":"2017-11-06T12:57:19.267","TickerTitle":"AUD/USD Intraday: key resistance at 0.7670.\r\n","Category":"Forex","TradePairName":"AUD/USD","Ticker":"AUD","TrendType":"THE upside prevails","Status":"Enabled","TrendValue1":"+1","PivotValue":0.767,"OurPreference":"v: short positions below 0.7670 with targets at 0.7635 & 0.7615 in extension.\r\n","AlternateScenario":"o: above 0.7670 look for further upside with 0.7695 & 0.7715 as targets.\r\n","Comments":" as long as 0.7670 is resistance, look for choppy price action with a bearish bias.\r\n","S1":0.7635,"S2":0.7615,"S3":0.7595,"R1":0.767,"R2":0.7695,"R3":0.7715,"Entry":0.0,"Stop":0.0,"T1":0.0,"T2":0.0},{"ID":133738,"TickerID":193,"CategoryID":3,"ClientID":5044,"TickerDateTime":"2017-11-06T12:55:54.33","TickerTitle":"Dollar Indexā€¸ (ICE) Intraday: bullish bias above 94.8000.\r\n","Category":"Forex","TradePairName":"Dollar Index (ICE)","Ticker":"DXA","TrendType":"THE upside prevails","Status":"Enabled","TrendValue1":"+1""PivotValue":94.8,"OurPreference":": long positions above 94.8000 with targets at 95.1500 & 95.3000 in extension.\r\n","AlternateScenario":"below 94.8000 look for further downside with 94.6500 & 94.4500 as targets.\r\n","Comments":": the RSI lacks downward momentum.","S1":94.8,"S2":94.65,"S3":94.45,"R1":95.15,"R2":95.3,"R3":95.45,"Entry":0.0,"Stop":0.0,"T1":0.0,"T2":0.0}]
Then i am trying to parse it to JSON and remove the 'd' at the beginning:
var json = JObject.Parse(rawJson);
var filter = json["d"];
var fff = filter["ID"];//Get the error here
Now I want to read the ID but for some reason it gives an error that it can't access child node.
Any idea why?
I think you need to check a few of your assumptions and try some break points.
Looking at the JSON returned by that API it looks like it's poorly formed and you are actually receiving a JSON array as a string:
{"d":"[{\"ID\":133739,\"TickerID\":23,\"CategoryID\":3,...}},
{\"ID\":133740,\"TickerID\":23,\"CategoryID\":3,...}},
[...]}]"}
Thus to parse it you'll first need to grab the value from the d parameter, and then parse that into an array:
// Get the response from the server
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
// Pass the response into a stream reader
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// Grab the JSON response as a string
string rawJson = reader.ReadToEnd();
// Parse the string into a JObject
var json = JObject.Parse(rawJson);
// Get the JToken representing the ASP.NET "d" parameter
var d = json.GetValue("d");
// Parse the string value of the object into a jArray
var jArray = JArray.Parse(d.ToString());
// At this point you can start looking for the items.
}
}
I have done something similar to this before however I'm not sure how to do this with a bigger project.
I'm trying to return the titles of all the stuff on the front page of reddit.
From this site:
http://www.reddit.com/r/all.json
I pasted the data into
http://json2csharp.com/#
to find out the class I need.
From here though, I'm not too sure on how to proceed. If I wanted to return an array of all this data so I can easily get information, how could I do it.
Sorry for the vagueness of this question but I'm just at a loss and don't know what to do.
Use
using (var webClient = new System.Net.WebClient()) {
var json = webClient.DownloadString("http://www.reddit.com/r/all.json");
}
For old .Net:
var request = WebRequest.Create(url);
string text;
request.ContentType = "application/json; charset=utf-8";
var response = (HttpWebResponse) request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
public void HttpsRequest(string address)
{
string data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
byte[] resp = new byte[(int)response.ContentLength];
Stream receiveStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(receiveStream, Encoding.ASCII))
{
data = reader.ReadToEnd();
}
}
I get an Arithmetic operation resulted in an overflow when I am trying to read a page over https. Errors occur because the response gives me ContentLenght = -1.
Using fiddler I can see that the page was received. Some other websites using HTTPS works fine but most of them not.
If I query https://www.google.com, I get the same error message, because not every response has a content length. Use this code to avoid the problem:
public static void HttpsRequest(string address)
{
string data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
data = reader.ReadToEnd();
}
}
}
This behavior is expected: not every response contains content length.
There is nothing in your sample that requires length to be known, so simply not reading it maybe enough.
From HttpWebResponse.ContentLength Property
The ContentLength property contains the value of the Content-Length header returned with the response. If the Content-Length header is not set in the response, ContentLength is set to the value -1.
If Content-Length header is not set it does not mean that you got a bad response.
public ActionResult GetGeoLocation(string address)
{
var uri = string.Format(
"http://maps.google.com/maps/api/geocode/json?address={0}&sensor=false",
HttpUtility.UrlEncode(address)
);
var request = (HttpWebRequest)HttpWebRequest.Create(uri);
var response = (HttpWebResponse)request.GetResponse();
return Json(response);
}
This code seems to call out just fine, but it's not returning the proper results? I must be missing something?
You are not reading the response data.
Use GetResponseStream to get the stream containing the body of the response.
var responseStream = response.GetResponseStream();
// read from responseStream
I am trying to make a POST request in which I am supposed to send Raw POST data.
Which property should I modify to achieve this.
Is it the HttpWebRequest.ContentType property. If, so what value should I assign to it.
public static string HttpPOST(string url, string querystring)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded"; // or whatever - application/json, etc, etc
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
try
{
requestWriter.Write(querystring);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
You want to set the ContentType property to the mime type of the data. If its a file, it depends on the type of file, if it's plain text then text/plain and if it's an arbitrary binary data of your own local purposes then application/octet-stream. In the case of text-based formats you'll want to include the charset along with the content type, e.g. "text/plain; charset=UTF-8".
You'll then want to call GetRequestStream() and write the data to the stream returned.