I generate request to a certain API which is mentioned here for sending an sms http://help.voxeo.com/go/help/evolution.sms.postapi
The request generates an XML response as follow
<rsp stat="ok">
<success msg="accepted" transactionid="2e47fe224d25559a696a7bdddec1828b" messageid="cf0d21f067e5b386a2e042134687eb5c"/>
</rsp>
I want to read if rsp stat in response is ok or fail how can i do it .
These are the first two lines how can i get particular xml tag out of response stream
HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();
Stream content = response.GetResponseStream();
Why not use XmlDocument to parse the XML. For example,
using(var reader = new StreamReader(content))
{
var doc = new XmlDocument();
doc.LoadXml(reader.ReadToEnd());
// you may want to compare case in-sensitive
if (doc.DocumentElement.Attributes["stat"].Value == "ok")
{
// success
}
}
(There is also Load method that would load from stream directly but I am not sure if it expects xml declaration at the beginning or not)
Yet another alternative is using XmlReader in case response could be lengthy and you wants to parse the initial bits as soon as its available.
try to read with XmlTextReader (http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader%28v=vs.71%29.aspx)
Related
First up, I'm not using the Xero api. This is more an OAuth2 questions than Xero specifically I think.
Not quite sure if the issue is a general OAuth2 problem or a Xero implementation of OAuth2. I can successfully authenticate, get my tokens etc from Xero. I can even make successful Get requests to their endpoints for Invoices and contacts. My problem is trying to POST anything, i.e. create an invoice.
The server responds with, 400 Bad request. I've confirmed by actual post data is correct by putting the XML into their API tester and all is good there.
Shouldn't a post request be a standard httpwebequest, (POST) with the query string ?oauth_signature=[sig here], and the actual post data URL encoded and sent via stream? Is my implementation correct and should I be looking elsewhere for the problem? Is the data sent in the form supposed to be included in the signature?
{
byte[] reqData = encode.GetBytes(postData);
HttpWebRequest request = WebRequest.CreateHttp(url + querystring) as HttpWebRequest;
request.Method = "POST";
try {
using (Stream stream = request.GetRequestStream) {
stream.Write(reqData, 0, reqData.Length);
}
using (HttpWebResponse response = request.GetResponse) {
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
dynamic responseFromServer = reader.ReadToEnd();
return responseFromServer;
}
} catch (Exception ex) {
}
}
Xero uses OAuth1.0a, rather than OAuth2. The OAuth signature needs to be supplied as a header rather than a query string. I believe it should be exactly the same as the successful GET requests you're making.
https://oauth.net/core/1.0a/#rfc.section.5.4.1:
The OAuth Protocol Parameters are sent in the Authorization header the following way:
Parameter names and values are encoded per Parameter Encoding.
For each parameter, the name is immediately followed by an '=' character (ASCII code 61), a '"' character (ASCII code 34), the parameter value (MAY be empty), and another '"' character (ASCII code 34).
Parameters are separated by a comma character (ASCII code 44) and OPTIONAL linear whitespace per [RFC2617].
The OPTIONAL realm parameter is added and interpreted per [RFC2617], section 1.2.
Update for those finding this now, Xero API now has OAuth2 in public Beta
https://developer.xero.com/documentation/oauth2/overview
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 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'm fairly new to ASP.NET. And I was wondering how I could go about getting xml from a site (Kuler's API in this case), and then post the result using AJAX?
So what I want here, is to be able to do a query to Kuler's API. The URL would be something like "http://kuler-api.adobe.com/rss/search.cfm?query="+queryVariable
Then send the resulting xml back to JS in some way.
Any pointers would be appreciated (:
What you'll need to do is have a handler that will perform the request for the XML and send it back to the browser using AJAX. It will act as an intermediary between server and client, and you won't have to worry about cross-domain policies.
This is what I do on one of my sites. I have a handler (let's call it proxy.ashx) that I call from a jQuery AJAX request. The proxy.ashx simply performs a WebClient.DownloadString action on the remote URL and sends the remote response (the XML) back to the client-side.
I think that Tim said enough, but what I would like to add is how you could do the server side request:
XmlDocument doc = new XmlDocument();
HttpWebRequest r = (HttpWebRequest)HttpWebRequest.Create("http://kuler-api.adobe.com/rss/search.cfm?query="+queryVariable);
r.Method = "POST";
using (Stream writeStream = r.GetRequestStream())
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(bodyRequest);
writeStream.Write(bytes, 0, bytes.Length);
}
try
{
using (HttpWebResponse response = (HttpWebResponse)r.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
doc.Load(readStream);
}
}
}
}
catch (WebException ex)
{
//Handle exception
}
I'd do the whole thing in Javascript using Jquery's ajax library, if possible. It's very simple to use and you don't have to worry about getting the XML from server to client that way.
Write a .net webservice (.asmx) that encapsulate the cross domain call, then call that service with AJAX.
I need to load an external web (not local) page into my site (some link), but only a part of it.
What are the options for doing so?
That depends on whether or not the external page is local, or on a different domain. If it's local, you can use $.load() in the jQuery library. This has an optional parameter to specify which element in the remote-dom to load it:
$("#links").load("/Main_Page #jq-p-Getting-Started li");
If the page is on another domain, you'll need a proxy script. You can do this with PHP and the phpQuery (php port of jQuery) library. You'll just use file_get_contents() to get the actual remote-dom, and then pull out the elements you want based on jQuery-like selectors.
$f = fopen('http://www.quran.az/2/255', 'r');
and so on...
Once you get the whole page as Michael Todd outlined, you will likely need to either use substring methods for a static means to slice up the content or you can use regex's for a more dynamic way to grab the content. An intro article on Regex's in ASP.Net can be found here. Good luck!
To load a web page in .Net, use the HttpWebRequest class.
Example taken from MSDN, here:
private string StringGetWebPage(String uri)
{
const int bufSizeMax = 65536; // max read buffer size conserves memory
const int bufSizeMin = 8192; // min size prevents numerous small reads
StringBuilder sb;
// A WebException is thrown if HTTP request fails
try
{
// Create an HttpWebRequest using WebRequest.Create (see .NET docs)!
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
// Execute the request and obtain the response stream
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
// Content-Length header is not trustable, but makes a good hint.
// Responses longer than int size will throw an exception here!
int length = (int)response.ContentLength;
// Use Content-Length if between bufSizeMax and bufSizeMin
int bufSize = bufSizeMin;
if (length > bufSize)
bufSize = length > bufSizeMax ? bufSizeMax : length;
// Allocate buffer and StringBuilder for reading response
byte[] buf = new byte[bufSize];
sb = new StringBuilder(bufSize);
// Read response stream until end
while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
sb.Append(Encoding.UTF8.GetString(buf, 0, length));
}
catch (Exception ex)
{
sb = new StringBuilder(ex.Message);
}
return sb.ToString();
}
Note that this will return the entire page and not just a portion of it. You'll then need to sift through the page to find the information you're looking for.