I download a json string from a website including a DateTime.
Using this code:
using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (Stream responseStream = httpWebResponse.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(responseStream))
{
value = streamReader.ReadToEnd();
}
}
}
authResponse = JsonConvert.DeserializeObject<Class1.Response>(value);
The Json Class looks like this:
public Response()
{
this.key = ""
this.valid_until = "";
this.xyz = "";
}
The String looks like this:
{
"key":"1424152",
"time_date":"2021-09-19 20:35:17",
"xyz":"Working"
}
Now before I Deserialize it I want to change the Date Time (add 2 days to it) in that string.
How would I approach that?
Related
I have an ASP.NET Web API 2 Project. I am trying to read Google Captcha from the form.
I tried this Code:
public string Post(FoundingRequest model)
{
var response = Request["g-recaptcha-response"];
string secretKey = "my key";
var client = new WebClient();
var result = client.DownloadString(
$"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={response}");
var obj = JObject.Parse(result);
model.Captcha = (bool)obj.SelectToken("success");
....
}
but I am receiving an Error on the first line:
Cannot apply indexing with [] to an expression of type
'HttpRequestMessage'
why? and how to solve it? thank you
That method's body for me works fine:
const string secretKey = "YOUR KEY";
string responseFromServer = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + response);
using (WebResponse resp = req.GetResponse())
using (Stream dataStream = resp.GetResponseStream())
{
if (dataStream != null)
{
using (StreamReader reader = new StreamReader(dataStream))
{
// Read the content.
responseFromServer = reader.ReadToEnd();
}
}
}
dynamic jsonResponse = new JavaScriptSerializer().DeserializeObject(responseFromServer);
return jsonResponse == null || bool.Parse(jsonResponse["success"].ToString());
Update
Regarding the comment, it can be checked on the client side
var response = window.grecaptcha.getResponse()
And then pass this variable to Web API
This is part of my client script:
if (typeof window.grecaptcha != 'undefined') {
var capResponse = window.grecaptcha.getResponse();
if (!capResponse || capResponse.length === 0) {
user.isCaptchaPassed = false;
//alert("Captcha not Passed");
return false;
}
user.gReCaptcha = capResponse;
}
"user" is JS object created before, which passed through JS to server. (AJAX call)
Here's how I did it. I don't use the ChallangeTs so I didn't bother
trying to figure out why it wasn't converting to DateTime properly.
Maybe someone else has that solved.
public class ReCaptchaResponse
{
public bool Success;
public string ChallengeTs;
public string Hostname;
public object[] ErrorCodes;
}
[HttpPost]
[Route("captcha")]
public bool Captcha([FromBody] string token)
{
bool isHuman = true;
try
{
string secretKey = ConfigurationManager.AppSettings["reCaptchaPrivateKey"];
Uri uri = new Uri("https://www.google.com/recaptcha/api/siteverify" +
$"?secret={secretKey}&response={token}");
HttpWebRequest request = WebRequest.CreateHttp(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 0;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string result = streamReader.ReadToEnd();
ReCaptchaResponse reCaptchaResponse = JsonConvert.DeserializeObject<ReCaptchaResponse>(result);
isHuman = reCaptchaResponse.Success;
}
catch (Exception ex)
{
Trace.WriteLine("reCaptcha error: " + ex);
}
return isHuman;
}
I found the answer, I created a hidden input with a certain name and updated its value on Captcha call back. Code:
<input type="hidden" value="" id="recaptcha" name="recaptcha" />
<div class="g-recaptcha" data-callback="imNotARobot" data-sitekey="key"></div>
and the Javascript is:
<script type="text/javascript">
var imNotARobot = function () {
$("#recaptcha").val(grecaptcha.getResponse());
};
</script>
server side:
public string Recaptcha { get; set; }
and the model binder does all the work.
I assume this request is coming from a form, change this:
var response = Request["g-recaptcha-response"];
To this:
var response = Request.Form["g-Recaptcha-Response"];
Also Change this:
var result = client.DownloadString($"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={response}");
To this:
var result = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
Following code returns entire JSON objects but I need to Filter to some specific Object, for example I need to get only the "layers" or tiltle can you please let me know how to do this is C#?
Do I have to create an HttpWebRequestobject for this? if so where should I pass the requested data?
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson");
Console.WriteLine(json);
}
I already tried this but it is also returning everything
class Program
{
private const string URL = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson";
private const string DATA = #"{{""layers"":""Layers""}}";
static void Main(string[] args)
{
CreateObject();
}
private static void CreateObject()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = DATA.Length;
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
requestWriter.Write(DATA);
}
try
{
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
Console.WriteLine(response);
Console.ReadLine();
}
}
}
}
catch (Exception e)
{
Console.WriteLine("-----------------");
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
If you need the info related to the layers array object then you can use following code
using (var wc = new WebClient())
{
string json = wc.DownloadString("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer?f=pjson");
dynamic data = Json.Decode(json);
Console.WriteLine(data.layers[0].id);
Console.WriteLine(data.layers[0].name);
Console.WriteLine(data.documentInfo.Title);
}
I am still trying to from a webservuce I have the following code crafted, but for some reason when it comes to the return value its null even though when i debug the xml string value it is indead there.
public XmlTextReader readXML(string postcode, string response, string accessCode)
{
WebRequest wrURL;
Stream objStream;
string strURL;
string url = "http://pcls1.craftyclicks.co.uk/xml/rapidaddress?postcode=" + postcode + "&response=" + response + "&key=" + accessCode;
wrURL = WebRequest.Create(url);
string xml = new WebClient().DownloadString(url);
objStream = wrURL.GetResponse().GetResponseStream();
StreamReader objSReader = new StreamReader(objStream);
strURL = objSReader.ReadToEnd().ToString(); #####but here it has the xml data ?####
XmlTextReader reader = new XmlTextReader(new StringReader(strURL));
return reader;#######here its empty ????#####
}
Edit
I am still not getting a response here but yet when i view it in the actual browser from the url produced within the code it displays the following
<CraftyResponse><address_data_formatted><delivery_point><organisation_name>THE BAKERY</organisation_name><department_name/><line_1>1 HIGH STREET</line_1><line_2>CRAFTY VALLEY</line_2><udprn>12345678</udprn></delivery_point><delivery_point><organisation_name>FILMS R US</organisation_name><department_name/><line_1>3 HIGH STREET</line_1><line_2>CRAFTY VALLEY</line_2><udprn>12345679</udprn></delivery_point><delivery_point><organisation_name>FAMILY BUTCHER</organisation_name><department_name/><line_1>7 HIGH STREET</line_1><line_2>CRAFTY VALLEY</line_2><udprn>12345680</udprn></delivery_point><delivery_point><organisation_name/><department_name/><line_1>BIG HOUSE, HIGH STREET</line_1><line_2>CRAFTY VALLEY</line_2><udprn>12345681</udprn></delivery_point><delivery_point><organisation_name/><department_name/><line_1>LITTLE COTTAGE</line_1><line_2>17 HIGH STREET, CRAFTY VALLEY</line_2><udprn>12345682</udprn></delivery_point><delivery_point_count>5</delivery_point_count><town>BIG CITY</town><postal_county>POSTAL COUNTY</postal_county><traditional_county>TRADITIONAL COUNTY</traditional_county><postcode>AA1 1AA</postcode></address_data_formatted></CraftyResponse>
I tried method 2 mentioned below but stil no luck
public XmlTextReader readXML(string postcode, string response, string accessCode)
{
string url = $"http://pcls1.craftyclicks.co.uk/xml/rapidaddress?postcode={postcode}&response={response}&key={accessCode}";
using (Stream objStream = WebRequest.Create(url)?.GetResponse().GetResponseStream())
{
return new XmlTextReader(new StringReader(new StreamReader(objStream)?.ReadToEnd()));
}//Dispose the Stream
}
Animated gif to show debuging
When working with IDisposable Objects you should consider using using
public XmlTextReader readXML(string postcode, string response, string accessCode)
{
string strURL = string.Empty;
string url = "http://pcls1.craftyclicks.co.uk/xml/rapidaddress?postcode=" + postcode + "&response=" + response + "&key=" + accessCode;
WebRequest wrURL = WebRequest.Create(url);
//string xml = new WebClient().DownloadString(url); //What is this for ? I dont see you using this in your code ?!
using(Stream objStream = wrURL.GetResponse().GetResponseStream())
{
using(StreamReader objSReader = new StreamReader(objStream))
{
return new XmlTextReader(new StringReader(objSReader.ReadToEnd()));
}//Dispose the StreamReader
}//Dispose the Stream
}
Try if the provided code fixes it.
EDIT:
To shorten your code you could use:
string url = $"http://pcls1.craftyclicks.co.uk/xml/rapidaddress?postcode={postcode}&response={response}&key={accessCode}";
using(Stream objStream = WebRequest.Create(url)?.GetResponse().GetResponseStream())
{
return new XmlTextReader(new StringReader(new StreamReader(objStream)?.ReadToEnd()));
}//Dispose the Stream
EDIT:
public XmlTextReader ReadXml(string postcode, string response, string accessCode)
{
//Create URL
string url = $"http://pcls1.craftyclicks.co.uk/xml/rapidaddress?postcode={postcode}&response={response}&key={accessCode}";
try
{
//Create WebRequest
WebRequest request = WebRequest.Create(url);
using (Stream responseStream = request.GetResponse().GetResponseStream())
{
if (responseStream != null)
{
using (TextReader textReader = new StreamReader(responseStream))
{
XmlTextReader reader = new XmlTextReader(textReader);
Debug.Assert(reader != null, "Reader is NULL");
return reader;
}
}
throw new Exception("ResponseStream is NULL");
}
}
catch (WebException ex)
{
//Handle exceptions here
throw;
}
}
Can you try this snippet ?
Side Note:
There is another overload in XmlTextReader which looks like this:
public XmlTextReader(string url);
public XmlTextReader readXML(string postcode, string response, string accessCode)
{
//Create URL
string url = $"http://pcls1.craftyclicks.co.uk/xml/rapidaddress?postcode={postcode}&response={response}&key={accessCode}";
return new XmlTextReader(url);
}
You can also try this one !
Im trying to create a very simple c# console application to post some data to a web api. However whatever I do I get an error on the response like:
responseText "{\"info\":{\"status\":\"failed\",\"error\":{\"code\":1000,\"message\":\"Invalid argument from request\"}}}" string
The api http://www.detrack.com/api-documentation/ is looking for a post like
https://app.detrack.com/api/v1/deliveries/view/all.json?key=dab13cc0094620102d89f06c0e464b7de0782bb979258d3a&json={"date":"2014-08-29"}
I know using this in chrome advanced rest application extension returns a valid result. But When I try the same via this console code. I get an error!.
Here is the code I have in my console application.
using System;
using System.Net;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://app.detrack.com/api/v1/deliveries/view/all.json?key=dab13cc0094620102d89f06c0e464b7de0782bb979258d3a&");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "json={\"date\":\"2014-08-28\"}";
Console.WriteLine(json);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
Console.ReadKey();
}
}
}
}
Any help/guidance would be really appreciated
brendan
So I'm looking at this:
string json = "json={\"date\":\"2014-08-28\"}";
And according to the brief description on detrack that is not what you want. They're expecting valid json and that isn't. Here's what you should be considering valid json:
string json = "{\"date\":\"2014-08-28\"}";
Be warned I don't know about your escaping of quotes. I would serialize that differently; either a strongly typed class or an anonymous class. Anon would look like this:
string json = JsonConvert.DeserializeObject(new { date = "2014-08-28" });
Setting aside any concerns about time, timezones, utc, etc, that will serialize your structures correctly. Here's a scratchy program from linqpad:
void Main()
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new { date = "2014-08-28"});
Console.WriteLine(json);
}
>>> {"date":"2014-08-28"}
You can try the (untested!) code below.
using System;
using System.Net;
using System.IO;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
var webAddr = "https://app.detrack.com/api/v1/deliveries/create.json";
var httpWebRequest = (HttpWebRequest) WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
string postData = "key=dab13cc0094620102d89f06c0e464b7de0782bb979258d3a&json={""date"":""2014-08-28""}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
httpWebRequest.ContentLength = byteArray.Length;
using(var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(byteArray, 0, byteArray.Length);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using(var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
MessageBox.Show(result);
}
}
}
}
I would like to ask if anyone know how to extract out the "name" and "query" and maybe store it in a arraylist.
Source file: https://api.twitter.com/1/trends/daily.json
You can use JObject , something like: -
string response = requestData("https://api.twitter.com/1/trends/daily.json");
JObject jsonResponse = new JObject();
var name = string.Empty;
var query = string.Empty;
try
{
jsonResponse = JObject.Parse(response);
name = (string)jsonResponse["name"];
query = (string)jsonRespone["query"];
}
catch
{
return "";
}
public string requestData(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string results = sr.ReadToEnd();
sr.Close();
return results;
}
Based on this question: Parse JSON in C#
Make a class that represents the JSON you're extracting, and extract the class from the JSON using the code in the JSONHelper class from the linked question:
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
ms.Close();
return obj;
}
}