Below is my responseFromServer,
{"version":3,"status":"ok","response":{"data":[{"address":"1908 Bull Temple Road","category_ids":[29],"category_labels":[["Community and Government","Education","Colleges and Universities"]],"country":"in","email":"principal#bmsce.ac.in","factual_id":"0c8c762c-52df-48d0-9add-1e6ef3f4df0d","fax":"080 2661 4357","hours":{"monday":[["7:00","15:00"]],"tuesday":[["7:00","14:00"]],"wednesday":[["7:00","13:00"]],"thursday":[["7:00","13:00"]],"friday":[["6:00","14:00"]],"saturday":[["7:00","14:00"]],"sunday":[["10:00","13:00"]]},"hours_display":"Mon 7:00-15:00; Tue 7:00-14:00; Wed-Thu 7:00-13:00; Fri 6:00-14:00; Sat 7:00-14:00; Sun 10:00-13:00","latitude":12.94172,"locality":"Bangalore","longitude":77.565889,"name":"BMS College of Engineering","postcode":"560019","region":"Karnataka","tel":"080 2662 2130","website":"http://www.bmsce.ac.in"},{"address":"R V Vidyanikethan Post, Mysore Road","category_ids":[29],"category_labels":[["Community and Government","Education","Colleges and Universities"]],"country":"in","email":"principal#rvce.ac.in","factual_id":"0389cc9b-0368-4ad7-8259-0c6021cd18d0","fax":"080 2860 0337","latitude":12.923694,"locality":"Bangalore","longitude":77.499105,"name":"R V College Of Engineering","postcode":"560059","region":"Karnataka","tel":"080 2860 1700","website":"http://www.rvce.ac.in"},"included_rows":1,"total_row_count":2}}
i am getting from the below code
WebRequest request = WebRequest.Create("RequestURL");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
Used:
dynamic json = JsonConvert.DeserializeObject(responseFromServer);
var data = json.response;
foreach (var album in data)
{
var address = album.address;
}
I can't deserialize the response. I want to get the data from the above Json. Any help would be appreciated. Thank you
Your json.response is not Enumerable. The property data in json.response is, you should use
var data = json.response.data as JArray
Related
I am trying to use an API and I don't have any problems with GET and POST but PUT isn't working. I tried with a lot of different examples and finally by chance I discovered that waiting more that 5 seconds (with 5000ms it is not working and with 5100ms it does) it starts working properly. But why is that happening? And how can I avoid this? 5 seconds for each registry update is to much waiting and I really don't understand why POST works well without waiting and PUT needs 5 seconds to work.
Here I put the method that I am using with the Thread.Sleep(5100). As I said without this line when I make WebResponse response = request.GetResponse(); gives me an error.
public void call(string url, object jsonObj)
{
try
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(urlSplio);
// Create POST data and convert it to a byte array.
request.Method = "PUT";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
request.Credentials = new NetworkCredential(WebConfigurationManager.AppSettings["User"], "WebConfigurationManager.AppSettings["Key"]");
string json = JsonConvert.SerializeObject(jsonObj);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
Thread.Sleep(5100);
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// 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();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
}
}
I think you might want to rewrite the response stream code
Take a look at this walkthrough on MS MS walkthrough
private byte[] GetURLContents(string url)
{
// The downloaded resource ends up in the variable named content.
var content = new MemoryStream();
// Initialize an HttpWebRequest for the current URL.
var webReq = (HttpWebRequest)WebRequest.Create(url);
// Send the request to the Internet resource and wait for
// the response.
// Note: you can't use HttpWebRequest.GetResponse in a Windows Store app.
using (WebResponse response = webReq.GetResponse())
{
// Get the data stream that is associated with the specified URL.
using (Stream responseStream = response.GetResponseStream())
{
// Read the bytes in responseStream and copy them to content.
responseStream.CopyTo(content);
}
}
// Return the result as a byte array.
return content.ToArray();
}
I am making a http post as follows
public async Task<string> HttppostJson()
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = HttpWebRequest.Create("URL") as HttpWebRequest;
// Set the Method property of the request to POST.
request.Method = "POST";
string post = "postData";
byte[] byteArray = Encoding.UTF8.GetBytes(post.ToString());
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
//Write data into a stream
using (var stream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null))
{
stream.Write(byteArray, 0, byteArray.Length);
}
// Pick up the response:
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
return result;
}
This gives me a JSON string as output. A small part of it is as follows
{
"id":20,
"title":"Testing after phase 2 is shifted to server",
"from":"Administrator",
"sendername":"ABX",
"day":"Tuesday",
"dateofMonth":"20th",
"month":"May",
"year":2014,
"date":"Tuesday, 20th May, 2014",
"content":"Ready. Set. Go"
}
There are 19 more such blocks refering to each "id". I want to deserialize the objects and populate them in a list view , only the "title" and "from" from all 20 notices should be seen in the listView. More id's will be added later so I want to make the listView dynamic which should include the new added id's and corresponding "title" and "from". So the listview should look like this
Title= "title"_corresponding_to_id
subtitle= "from"_correspondin_to_id
Title= "title"_corresponding_to_id
subtitle= "from"_correspondin_to_id
Title= "title"_corresponding_to_id
subtitle= "from"_correspondin_to_id
..
..
..
I am new to Windows app development. SO needed a little help.
You can make Movie class.
Then you can use newtonsoft's Json.NET library and use JObject class.
You just save json response into a string and then get values from JObject and add it to list.
string json = someJsonText
JObject response = JObject.Parse(json);
List<Movie> list = new List<Movie>();
Movie first = new Movie();
first.Title = response.GetValue("title");
list.Add(first);
And do that in foreach or for sentence to get, create and save all the movies.
Iam developing a cross platform android app in Xamarin. I want to send a request to register my device. Iam sending my DeviceId, DeviceName and EncodedAccountName i.e my email id.
But I dont get any response. I have tested the request on Postman and get a proper response.
Here is my code:
StringBuilder registerContent = new StringBuilder();
registerContent.Append("DeviceId=").Append(deviceId).Append("&");
registerContent.Append("Name=").Append(deviceName).Append("&");
registerContent.Append("EncodedAccountName=").Append(username);
WebRequest request = WebRequest.Create(EndPoints.RegisterDeviceEndPoint);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = registerContent.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType= "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.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 = request.GetResponse();// Dont get any response here
// Display the status.
System.Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// 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();
// Display the content.
System.Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return response.ToString();
Any ideas on what might me going wrong?
Thanks
This is how I notify my Web API and wait for a string response:
string myParameters = "?firstParam=" + someParam1 + "&secondParam=" + someParam2;
string url = someHTTPAddress + myParameters;
stringResponseFromWebAPI = (new WebClient()).DownloadString(url);
I send web request with this code :
WebRequest request = WebRequest.Create(url);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Response.Write(responseFromServer);
But I received wrong data such as &�F� ��S|�"�i�(�
what is the solution?
string accessToken = GetAccessToken();
string accessKey = accessToken.Split('=')[1];
var client = new FacebookClient(accessKey);
dynamic me = client.Get("me");
here is the method to get access token and it does return a valid access token
private static string GetAccessToken()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=201193246663533&client_secret=secretkeyhere");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.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 = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// 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();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
However, when I debug over
dynamic me = client.Get("me");
throws this exception:
(OAuthException - #2500) An active access token must be used to query information about the current user.
How can i fix this?
you are getting access token for the APPLICATION, not for a user. Therefore, "me" does not make sense. You should supply ID there - either your user ID, or your app ID, or any other ID your app has permissions for.
both calls worked for with your example:
dynamic me = client.Get("1000<<MY_USER_ID>>5735");
dynamic theApp = client.Get("201193246663533");