Hey guys I have the following code working which is sending a GET Request and receiving JSON Response.
Now I can basically go
GetWeatherByLocation(53.3, -6.28);
and the method returns
{"status":"OK","url":"http://www.link.com/areas/rathfarnham-11","name":"Rathfarnham"}
I was now wondering how can I retrieve the values for
URL
Name
from the string returned
THanks a lot
Im using ASP.NET 2 this is my calling code
public static string GetWeatherByLocation(double lat, double lng)
{
string formattedUri = String.Format(CultureInfo.InvariantCulture,
FindNearbyWeatherUrl, lat, lng);
HttpWebRequest webRequest = GetWebRequest(formattedUri);
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
jsonResponse = sr.ReadToEnd();
}
return jsonResponse;
}
Your calling code is in javascript, i guess. Just use the response as a javascript object, because the json format is a notation for a javascript object. You can access its properties directly:
var returningValue = {"status":"OK","url":"http://www.link.com/areas/rathfarnham-11","name":"Rathfarnham"} ;
alert(returningValue.status);
alert(returningValue.url);
alert(returningValue.name);
edit: if you want to parse json in .net you can see this question where somebody explains how to parse the object using JavaScriptSerializer from System.Web.Extensions.dll
edit 2: if your version of .net doesn't let you play with this .dll i'd recommend looking into json.net previous releases, notably the last 2.0 release. But you should have access to the dll since it appeared in .net 2.0, albeit in the AJAX framework if my memory is good...
It's possible to parse your object by hand, but i'd really recommend using a library instead. If you want to do it by hand, you're in a complex world...
Related
I am currently trying to wrap an internal API and make it external. To do so, I am trying to relay the JSON responses from the internal API and send that exact response when someone makes a get request. Instead, ASP .NET is JSONifying that son and adding extra back slashes as escape characters (when in fact those slashes are really escape slashes put in by the internal api).
How can i get it so asp does not jsonify the string
You can write your json data directly to response and set right content headers.
public HttpResponseMessage GetData()
{
var json = "\"value\": \"da\\ta\"";
var resp = Request.CreateResponse(HttpStatusCode.OK);
resp.Content = new StringContent(json);
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
resp.Content.Headers.ContentEncoding = //your json encoding, you can get it from response inner API
return resp;
}
I am wroking on asp.net core web api and I am new in asp.net core. I make a web api and want to call it from web application controller and its works good. My problem is I want to convert json in c# object list. I already get a json format from web api, but enable to convert it into c# object list. I google a lot and find one solution in everywhere and that is
JsonConvert.DeserializeObject<BusinessUnit>(result);
Which is not working for me. My Code :
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync(baseAddress + "/api/BusinessUnit");
var result = response.Content.ReadAsStringAsync();
List<BusinessUnit> businessunits = JsonConvert.DeserializeObject<BusinessUnit>(result); //result shows error because it needs string as parameter.
I am still trying but enable to solve this problem.
How can I convert "result(json format)" in c# object list "businessunits" ?
Thanks in advance.
You need to await the task like so:
var result = await response.Content.ReadAsStringAsync();
Danger of using var, as now it inferred the type as Task<string>. If you had tried:
string result = response.Content.ReadAsStringAsync();
It would have immediately given you an error that it can't cast Task<string> to string.
EDIT: The other error you have is that you are trying to deserialize the JSON into an object when it is actually an array.
List<BusinessUnit> businessunits = JsonConvert.DeserializeObject<List<BusinessUnit>>(result);
In .NET Core this is done as:
var units = await result.Content.ReadFromJsonAsync<List<BusinessUnit>>();
You can use .Result to convert in string :
string XYZ = response.Content.ReadAsStringAsync().Result;
You could try this:
IEnumerable<BusinessUnit> result = await response.Content.ReadAsAsync<IEnumerable<BusinessUnit>>();
Saludos.
I have given
[WebGet(UriTemplate = "/{year}/{issue}/{article}")]
Article GetArticle(string year, string issue, string article);
[OperationContract]
[WebInvoke(UriTemplate = "/{year}/{issue}",Method="POST")]
Article AddArticle(string year, string issue, Article article);
My URL is http://localhost:1355/Issues.svc/
if I give this I am fetching all data from the database
http://localhost:1355/Issues.svc/2010/June/A
GetArticle method fires for the filtered data to bring from db.
Similarly I have to call the Add Article(WebInvoke) method to insert data in to the database.
How should I call this method in the browser
how my url should be should I give method=post
check this post help you to achieve the task you want :Create REST service with WCF and Consume using jQuery
You won't be able to send an HTTP post from a browser by just modifying the URL. You'll have to have a web page with a HTML form, some Javascript code, some server-side code, or something else that has the ability to make an HTTP POST request to your service URL.
If you are just wanting to test your service while in development, here's a good HTTP debugging tool that you might want to check out: http://fiddler2.com
You can't use post it using browser url.
Try this code
//Creating the Web Request.
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://localhost/DemoApp/Default.aspx") as HttpWebRequest;
//Specifing the Method
httpWebRequest.Method = "POST";
//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "Username=username&password=password";
//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
Source : http://www.dotnetthoughts.net/2009/11/10/post-data-using-httpwebrequest-in-c-sharp/
I have a web service sitting on a dev machine written in python. I am trying to access said webservice using asp.net via the server side. the webservice has been tested and works in every other instance. but when I hit it via asp.net using a post method asp.net doesn't seem to be sending the post values to the webservice at all, everything else is sent fine. If I run the exact same code in a console application everything works 100%.
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Text;
class WebService {
static public String GetContent(String user_id, String content_id) {
Uri address = new Uri("http://url.to.api/");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
String response_text = String.Empty;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = new NetworkCredential("username", "password");
string data = string.Format("userid={0}&contentid={1}", user_id, content_id);
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream()) {
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
StreamReader reader = new StreamReader(response.GetResponseStream());
response_text = reader.ReadToEnd();
}
return response_text;
}
}
updated * with the class more or less thats being used. "url, user/pass".
Also we have checked the information going back and fourth and the webservice never sees the post data... this code as is ran on both a console app and in a asp.net project both hit the webservice, both get a response. the console gets a response with valid information showing that its working, the asp.net project runs and receives and error stating that userid isn't being passed. We have dozens of other sites hitting this webservice with no issues, except non are written in asp.net.
Use a proxy such as Fiddler to view the HTTP transaction between your app and the web service. That should give you a better idea of which end the error is on, and its nature.
You may consider running this against a test "Hello World" service just to test communcations.
Also, post your real code. Change the uri if you want, but what you've quoted above won't compile. The problem may be outside of this snippet.
update
How long is it taking for you to receive a reply? Timeout? Running out of connections?
Our Situation:
Our team needs to retrieve log information from a 3rd party website (Specifically, this log
information is call logs -- our client rents an 866 number. When calls come in, they assist
people and need to make notes accordingly in our application that will correspond with the
current call). Our client has a web account with the 3rd party that allows them to view the
current call logs (date/time, phone number, amount of time on each call, etc).
I contacted the developer of their website and inquired about API or any other means of syncing
our database with their constantly updating database. They currently DO NOT support API. I
informed them of my situation and they are perfectly fine with any way we can retrieve the
information (bot/crawler). *The 3rd party said that they are working on API but could not give
us a general timeline as to when it will be up... and as with every client, they need to start
production ASAP.
I completely understand that if the 3rd party were to change their HTML layout, it may cause a
slight headache for us (sorting the data from the webpage). That being said, this is a temporary
solution to a long term issue. Once they implement their API, we will switch them over to it.
So my question is this:
What is the best way to log into the 3rd party website (see image: http://i903.photobucket.com/albums/ac239/jreedinc/customtf.jpg)
and retrieve certain HTML pages? We have reviewed source codes of webcrawlers, but none of them
have the capability of storing cookies and posting information back to the website (with log in information). We would prefer to do this in ASP.NET.
Is there another way to accomplish logging on to the website, then retrieving said information?
The classes you'll need to use are in the System.Net namespace. Below is some quick and dirty proof of concept code. To login in to a site that uses form login + cookies for security and then scrape the HTML output of a page.
In order to parse the HTML results you'll need to use an additional tool.
Possible HTML parsing tools.
SgmlReader, can convert HTML to XML. You then use .NET's XML features to extract data from the XML.
http://code.msdn.microsoft.com/SgmlReader
HTML Agility Pack, allows XPath queries against HTML documents.
http://htmlagilitypack.codeplex.com/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class WebWorker {
/// <summary>
/// Cookies for use by web worker
/// </summary>
private System.Collections.Generic.List `<System.Net.Cookie` > cookies = new List < System.Net.Cookie > ();
public string GetWebPageContent(string url) {
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(url);
System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
request.CookieContainer = cookieContainer;
request.Method = "GET";
//add cookies to maintain session state
foreach(System.Net.Cookie c in this.cookies) {
cookieContainer.Add(c);
}
System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader sReader = new System.IO.StreamReader(responseStream);
System.Diagnostics.Debug.WriteLine("Content:\n" + sReader.ReadToEnd());
return sReader.ReadToEnd();
}
public string Login(string url, string userIdFormFieldName, string userIdValue, string passwordFormFieldName, string passwordValue) {
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(url);
System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
request.CookieContainer = cookieContainer;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string postData = System.Web.HttpUtility.UrlEncode(userIdFormFieldName) + "=" + System.Web.HttpUtility.UrlEncode(userIdValue) +
"&" + System.Web.HttpUtility.UrlEncode(passwordFormFieldName) + "=" + System.Web.HttpUtility.UrlEncode(passwordValue);
request.ContentLength = postData.Length;
request.AllowAutoRedirect = false; //allowing redirect seems to loose cookies
byte[] postDataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
System.IO.Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse;
// System.Diagnostics.Debug.Write(WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader sReader = new System.IO.StreamReader(responseStream);
System.Diagnostics.Debug.WriteLine("Content:\n" + sReader.ReadToEnd());
this.cookies.Clear();
if (response.Cookies.Count > 0) {
for (int i = 0; i < response.Cookies.Count; i++) {
this.cookies.Add(response.Cookies[i]);
}
}
return "OK";
}
} //end class
//sample to use class
WebWorker worker = new WebWorker();
worker.Login("http://localhost/test/default.aspx", "uid", "bob", "pwd", "secret");
worker.GetWebPageContent("http://localhost/test/default.aspx");
I used a tool recently called WebQL (its a web scraper tool that lets the developer use SQL like syntax to scrape information from web pages.
WebQL on Wikipedia
This is actually a relatively simple operation. What you need to do is get the page that the screenshot posts back to (something like login.php, etc) and then construct a webrequest to that page with the login data you have. You will most likely get back a cookiecontainer that will have your login cookie to use on all subsequent requests.
You can look at this MSDN article for the basics of how to do it, but their write-up is kind of confusing. Look at the community comments at the end for an example of how to post back page variables (like the username and password). You will need to make sure you pass the cookiecontainer around on subsequent requests.
Unfortunately .NET does not natively have something like WWW::Mechanize, but the Webclient does have an "upload value" which might make it easier. You will still have to manually parse the page to figure out what fields you need to pass.