I just started playing around with some API's in C#. In my form I had added a service reference http://wsf.cdyne.com/WeatherWS/Weather.asmx. Everything works great and I am able to utilize its library. Now I am trying to use for example http://free.worldweatheronline.com/feed/apiusage.ashx?key=(key goes in here)&format=xml. [I have a key] Now when I try to use it as service reference I am not able to use.
Do I have to call it in my form instead of referencing it? or do some sort of conversion? Also does it matter if its xml or json type?
ASMX is old technology and uses SOAP under the hood. SOAP doesn't tend to work with query string parameters, it takes parameters as part of the message.
ASHX is something different (it could be anything, it's one way to write a raw HTML/XML page in .NET), so you can't transfer the method for calling one to the other. It also won't have a service reference, it's likely you request it via a raw HTTP request. You'll need to consuly the service documentation to discover how to use it.
worldweatheronline doesn't return a SOAP-XML that is consumable by a WebService client. Therefore you should download the response and parse it as done with many REST services.
string url = "http://free.worldweatheronline.com/feed/apiusage.ashx?key=" + apikey;
using (WebClient wc = new WebClient())
{
string xml = wc.DownloadString(url);
var xDoc = XDocument.Parse(xml);
var result = xDoc.Descendants("usage")
.Select(u => new
{
Date = u.Element("date").Value,
DailyRequest = u.Element("daily_request").Value,
RequestPerHour = u.Element("request_per_hour").Value,
})
.ToList();
}
Also does it matter if its xml or json type?
No, at the end you have to parse the response by yourself.
string url = "http://free.worldweatheronline.com/feed/apiusage.ashx?format=json&key=" + apikey;
using (WebClient wc = new WebClient())
{
string json = wc.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(json);
var jArr = (JArray)dynObj.data.api_usage[0].usage;
var result = jArr.Select(u => new
{
Date = (string)u["date"],
DailyRequest = (string)u["daily_request"],
RequestPerHour = (string)u["request_per_hour"]
})
.ToList();
}
PS: I used Json.Net to parse the json string
Related
I've a problem as I need to send some json to a url. When I send all my json and token to the page.
Then there will be no content JSON value into the system.
I have checked up on whether there is some content and it is there, but it sends just do not like json values.
string apiKeyToken = model.reepaytoken; // TOKEN HERE.
string URLLink = APIClassPay.HelperPay.CreateCustomerURL;//URL to send it json to.
WebClient client = new WebClient();
//JSON coming here!
var JSONCustomer = APIClassPay.HelperPay.CreateCustomer(model.Brugernavn, model.Adresse, model.Byen, model.Postnr.ToString(), model.Mobil.ToString(), model.Fornavn, model.Efternavn);
client.Headers.Add("text/json", JSONCustomer);
client.Headers.Set("X-Auth-Token", apiKeyToken);
string reply = client.DownloadString(URLLink);
When I blow my json looks like this.
[HttpPost]
public ActionResult information(BuyMedlemskabViewModel model)
{
DataLinqDB db = new DataLinqDB();
var Pric = db.PriceValues.FirstOrDefault(i => i.id == model.HiddenIdMedlemskab);
if (Pric != null)
{
string _OrderValue = DateTime.Now.Year + Helper.Settings.PlanValue();
Session[HelperTextClass.HelperText.SessionName.OrderId] = _OrderValue;
Session[HelperTextClass.HelperText.SessionName.FakturaId] = model.HiddenIdMedlemskab;
Session[HelperTextClass.HelperText.SessionName.fornavn] = model.Fornavn;
Session[HelperTextClass.HelperText.SessionName.efternavn] = model.Efternavn;
Session[HelperTextClass.HelperText.SessionName.Adresse] = model.Adresse;
Session[HelperTextClass.HelperText.SessionName.Post] = model.Postnr;
Session[HelperTextClass.HelperText.SessionName.Byen] = model.Byen;
Session[HelperTextClass.HelperText.SessionName.Mobil] = model.Mobil;
string apiKeyToken = model.reepaytoken;.
string URLLink = APIClassPay.HelperPay.CreateCustomerURL;//URL to send it json to.
WebClient client = new WebClient();
//JSON coming here!
var JSONCustomer = APIClassPay.HelperPay.CreateCustomer(model.Brugernavn, model.Adresse, model.Byen, model.Postnr.ToString(), model.Mobil.ToString(), model.Fornavn, model.Efternavn);
client.Headers.Add("text/json", JSONCustomer);
client.Headers.Set("X-Auth-Token", apiKeyToken);
string reply = client.DownloadString(URLLink);
}
return RedirectToAction("information");
}
EDIT - Update (ERROR HERE):
ReePay API reference: https://docs.reepay.com/api/
I think there are a few things, you'll have to fix:
First of all you're obviously trying to create a ressource (usually a POST or PUT, speaking in REST-words but you're using WebClient's DownloadString-method which performs a GET. So I think you should probably use a POST or PUT instead but which one to chose exactly depends on the web service you're contacting.
Then you seem to have mistaken the Content-Type-header and tried to pack the payload in there. The payload - your customer JSON - will have to be put into the request's body.
Based on your previous questions I assume the service you're trying to contact is either PayPal or QuickPay. To further help you with this question, it'd be helpful if you could specify which one you use.
If it's QuickPay, please notice that there's an official .NET client which you could use instead of using WebClient on you own.
But anyway for making HTTP requests I'd suggest you to use HttpClient in favor of WebClient. You'd generally do it in a way like this:
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post,
APIClassPay.HelperPay.CreateCustomerURL);
request.Headers.Add("X-Auth-Token", apiKeyToken);
request.Headers.Add("Content-Type", "application/json");
request.Content = new StringContent(JSONCustomer);
var response = await httpClient.SendAsync(request);
}
EDIT:
As you clarified in a comment, the service you're using is Reepay. If you take a look at the documentation of the create customer method, you can see, that the necessary HTTP method is POST. So the code snippet above should generally fit.
Regarding the compilation error you faced, I updated the code-snipped above. There was a mistake in the variable names I chose. Please note, that you dropped the keyword await as I can see from your screenshot. Please re-enter it. If the compiler complains about it, it's very likely that the .NET framework version of your project is less than 4.5 which is necessary to use async/await.
So you should update your project's .NET framework version at best to version 4.6.1 as Microsoft recently announced that support for 4.5 and others is discontinued. Have a look here on how to do that.
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(url, "sign=fsadfasdf&charset=utf-8");
}
Server can get value of sign and charset.
But there is a third parameter LIST, which is a list of object (this object is an entity class).
How can I pass this parameter to the server?
I tried to use "sign=fsadfasdf&charset=hhh&list=" + Json(list) as postData (convert List to json string). But the server didn't get value of this list param.
I hate to post 1 line answers with links in them but this has been solved on here before ...
POSTing JsonObject With HttpClient From Web API
HttpClient class is designed to solve exactly this problem, i believe its found in the nuget package "Microsoft.AspNet.WebApi.Client", this should add the namespace "System.Net.Http" to your project.
It's also geared at being completely async which should be nicer to your server!
EDIT:
To post an array / collection you would do something like this ...
var myObject = (dynamic)new JsonObject();
myObject.List = new List<T>();
// add items to your list
httpClient.Post(
"",
new StringContent(
myObject.ToString(),
Encoding.UTF8,
"application/json"));
I have installed "vivekn sentimental tool" which is running in my local host.when we send an http request using unirest post method to the server which contains a string it sends response whether it is positive or negative.I had used it in java.but anyone tell me how to use that in c#
here is my java code
HttpResponse request = Unirest.post("http:localhost:1681/api/text/")
.header("X-Mashape-Authorization", "xxxxxxxxxx")
.field("txt", "i like icecream").asJson();
JSONObject js = new JSONObject(request.getBody().toString());
Object ob = js.get("result");
JSONObject job = new JSONObject(ob.ToString);
String sentiment = (String)job.get("sentiment");
what I need is I want to send a request to the localhost and receive a response which is json with or without using unirest
It's going to roughly look something like this:
using (var wc = new WebClient())
{
wc.Headers.Add(
"X-Mashape-Authorization", "1R1tvmPFLFL7brrvfO9jvsqnvhiVggAn");
var body = wc.DownloadString("http:localhost:1681/api/text/");
var js = Newtonsoft.Json.Linq.JObject.Parse(body);
/* do something with the json */
}
You'll need to get the Newtonsoft library from NuGet - ID: "Newtonsoft.Json".
My web application needs to be able to go and get all my projects from Paymo http://api.paymo.biz/
I am familiar with JSON and XML, but what I'm wondering is, how does one interact with the api (make calls to it).
I would ideally like to make a class in ASP .Net such as PaymoManager(int apikey....)
From there I can wrap the functionality I need. I just need to understand, how do I call functions of the API and how do I get the response. I am not familar with web apis.
Edit: Could you give me an example of this, even with some abstract url. I need this done server side in a CS file.
Basically a simple example that calls someurl.com/somerequest and then how do you receive the JSON or XML... how does this work in terms of a class. I want this in a class.
http://api.paymo.biz/docs/misc.overview.html
To perform an action using the Paymo API, you need to send a request
to the Paymo webservice specifying a method and some arguments, and
will receive a formatted response.
This means that you can use WebClient to download a string from a url:
WebClient client = new WebClient();
string reply = client.DownloadString (address);
Depending on the format you specify, you can parse the reply as XML or JSON.
XDocument xml = XDocument.Parse(reply);
// where ReplyType is a class that defines public
// properties matching the format of the json string
JavaScriptSerializer serializer = new JavaScriptSerializer();
ReplyType abc = serializer.Deserialize<ReplyType>(reply);
If you are using .NET 4.5, you might consider using HttpClient like so:
static async void Main()
{
try
{
// Create a New HttpClient object.
HttpClient client = new HttpClient();
// fill in the details in the following string with your own KEY & TOKEN:
string requestUrl = "https://api.paymo.biz/service/paymo.auth.logout?api_key=API_KEY&format=JSON&auth_token=AUTH_TOKEN"
HttpResponseMessage response = await client.GetAsync(requestUrl );
response.EnsureSuccessStatusCode();
string responseBodyJSON = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method in following line
// string body = await client.GetStringAsync(uri);
Console.WriteLine(responseBodyJSON );
// Now you can start parsing your JSON....
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
I'm having this strange problem when i try to access elements in json from javascript. i retreve a json string from a url like so,
// Create Request
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(#"www.someurl.com");
// Create Client
WebClient client = new WebClient();
// Assign Credentials
client.Credentials = new NetworkCredential("username", "pass");
// Grab Data
sjson = client.DownloadString(#"www.someurl.com");
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
oSerializer.MaxJsonLength = Int32.MaxValue;
sjson = oSerializer.Serialize(sjson);
But when i access this sjson variable from javascript in html code, it doesn't return anything, but if i hard code it, it returns the values, please help on this one. I tried many things but didn't work. I also tried to just pass the retreieved json string without serializing, when i do that the javascript stops working. :( following is the javascript code,
<script type="text/javascript">
var jsons = JSON.parse('<%=sjson%>');
function initialize() {
alert("hahahahaaa");
document.writeln(jsons.Body[0].RowId.SensorIdValue);
//document.writeln(myobject.Body[0].RowId.SensorIdValue);
}
</script>
The issue is
document.writeln(myobject.Body[0].RowId.SensorIdValue);
returns a value if i use the myobject variable, but
document.writeln(jsons.Body[0].RowId.SensorIdValue);
returns nothing when i use it with the parsed value. :(
following is the sample of the json output (response.write) i get after running the serializer via c#,
Please help me on this one..i cant seem to find the problem here.
EDIT:
if it help, the fiollowing is the json string i get straight from the server witout making any serializations,
Few contents of the question have been removed due to owner request
What you're seeing there is doubly JSON-serialized data. You retrieved JSON from the remote server and then JSON encoded it a second time with JavaScriptSerializer. This is a post I wrote about that, in the context of ASMX ScriptServices, which explains in more detail: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/. Your case isn't exactly the same, but the end result is.
Remove the JavaScriptSerializer code and return the JSON string you retrieved (sjson) instead of serializing it a second time.
You don't need to use a Json serializer because the remote server already returns a JSON encoded string that you could directly use in your page and avoid the double encoding.
So:
public string GetJson()
{
// Create Client
using (WebClient client = new WebClient())
{
// Assign Credentials
client.Credentials = new NetworkCredential("username", "pass");
// Grab Data
return client.DownloadString(
#"www.someurl.com"
);
}
}
and then:
<script type="text/javascript">
var jsons = <%= GetJson() %>;
function initialize() {
alert("hahahahaaa");
document.writeln(jsons.Body[0].RowId.SensorIdValue);
//document.writeln(myobject.Body[0].RowId.SensorIdValue);
}
</script>