i m facing a problem with WebResponse Property it is not properly updating in my Windows phone 7 application.
ReceiveData() // I m calling this Function recursively, With Timer.
{
strurl = "http://www.***Mylivedatawebsite.com/api/rates.php";
webRequest = (HttpWebRequest)WebRequest.Create(strurl);
webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}
FinishWebRequest(IAsyncResult result)
{
WebResponse resp = webRequest.EndGetResponse(result);
StreamReader objReader = new StreamReader(resp.GetResponseStream());
XDocument Doc = XDocument.Load(objReader);
}
The Doc contains the same value after parsing. Please help me out.
In a windows phone 7, usually the webservice response is cached. You can use incremental approach in the url's attribute. Here's the sample below.
static int increment= 0;
strurl = "http://www.***Mylivedatawebsite.com/api/rates.php"+ "id =" + (increment++).ToString();
In this way when the webservice wil see a different attribute id then it will make a re-request to the server.
Related
I am working on a c# console application where I am making a Http Post request to a web api by using xml file and I'm kind of new to XML and web services but I figured out the following code for the request but failed to pass xml data to the method
static void Main(string[] args)
{
string desturl=#"https://xyz.abcgroup.com/abcapi/";
Program p = new Program();
System.Console.WriteLine(p.WebRequestPostData(desturl, #"C:\Applications\TestService\FixmlSub.xml"));
}
public string WebRequestPostData(string url, string postData)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()))
{
return sr.ReadToEnd().Trim();
}
}
}
For obvious reasons the above code throws 404 error as I think I am not passing the xml data properly
May I know how I can fix this?
You're not posting xml, your posting the string C:\Applications\TestService\FixmlSub.xml
Change your method call from:
System.Console.WriteLine(p.WebRequestPostData(desturl, #"C:\Applications\TestService\FixmlSub.xml"));
to
var xml = XElement.Load(#"C:\Applications\TestService\FixmlSub.xml");
System.Console.WriteLine(p.WebRequestPostData(desturl, xml.ToString(SaveOptions.DisableFormatting));
If you are trying to learn post / receive, go for it. But there are open source libraries that are already well tested to use if you want to use them.
The non-free version of Servicestack.
And their older free-version. I think the older free version is great. I've never tried the newer one. You deal with objects, like say an Employee and pass that to the library and it does the translation to xml or whatever the web-service wants.
You can post whole strings if you want. They have great extension methods to help you with that too.
I have tried both WebClient's DownloadSring and WebRequest+Stream to try and scrape a page (This one) and get the Raw Paste data from it. I have scoured the net but have found no answers.
I have this code:
WebRequest request = WebRequest.Create("http://pastebin.com/raw.php?i=" + textBox1.Text);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string pasteContent = "";
using (StreamReader sr = new StreamReader(data))
{
pasteContent = sr.ReadToEnd();
}
new Note().txtMain.Text += pasteContent;
new Note().txtMain.Refresh();
and I have multiple forms so I am editing Note's txtMain textbox to add the paste content but it seems to return nothing, no matter which function I use. I know cross-form editing works because I have multiple things that can return to it.
How can I scrape the raw data?
Thank you VERY much,
P
There is no problem in downloading the content of your site. You simply doesn't use the instance of the Node class you created.
var note = new Note();
note.txtMain.Text += pasteContent;
note.Show();
I am new to C# so I was wondering if someone can help me out on this. I am trying to send HttpPost from Windows Phone 8 to the server. I found two examples that I would like to combine.
The first one is an example of sending Http Post (http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx). The problem with this one is that it is not support by Windows Phone 8.
The second example is using the BeginGetResponse (http://msdn.microsoft.com/en-us/library/windowsphone/develop/system.net.httpwebrequest(v=vs.105).aspx). This supports windows phone 8.
I need to convert the second example into a BeginGetRequestStream() like the first example. I will try to figure out this myself, but I am posting online if someone already knows how to do this. I am sure this will be helpful for other WP8 developers.
Update
I am now trying to get response from the server. I have started a new question. Please follow this link (Http Post Get Response Error for Windows Phone 8)
I am also currently working on a Windows Phone 8 project and here is how I am posting to a server. Windows Phone 8 sort of has limited access to the full .NET capabilities and most guide I read say you need to be using the async versions of all the functions.
// server to POST to
string url = "myserver.com/path/to/my/post";
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
//create some json string
string json = "{ \"my\" : \"json\" }";
// convert json to byte array
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);
// Write the bytes to the stream
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
I propose a more generic asynchronous approach supporting success and error callbacks here:
//Our generic success callback accepts a stream - to read whatever got sent back from server
public delegate void RESTSuccessCallback(Stream stream);
//the generic fail callback accepts a string - possible dynamic /hardcoded error/exception message from client side
public delegate void RESTErrorCallback(String reason);
public void post(Uri uri, Dictionary<String, String> post_params, Dictionary<String, String> extra_headers, RESTSuccessCallback success_callback, RESTErrorCallback error_callback)
{
HttpWebRequest request = WebRequest.CreateHttp(uri);
//we could move the content-type into a function argument too.
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
//this might be helpful for APIs that require setting custom headers...
if (extra_headers != null)
foreach (String header in extra_headers.Keys)
try
{
request.Headers[header] = extra_headers[header];
}
catch (Exception) { }
//we first obtain an input stream to which to write the body of the HTTP POST
request.BeginGetRequestStream((IAsyncResult result) =>
{
HttpWebRequest preq = result.AsyncState as HttpWebRequest;
if (preq != null)
{
Stream postStream = preq.EndGetRequestStream(result);
//allow for dynamic spec of post body
StringBuilder postParamBuilder = new StringBuilder();
if (post_params != null)
foreach (String key in post_params.Keys)
postParamBuilder.Append(String.Format("{0}={1}&", key, post_params[key]));
Byte[] byteArray = Encoding.UTF8.GetBytes(postParamBuilder.ToString());
//guess one could just accept a byte[] [via function argument] for arbitrary data types - images, audio,...
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
//we can then finalize the request...
preq.BeginGetResponse((IAsyncResult final_result) =>
{
HttpWebRequest req = final_result.AsyncState as HttpWebRequest;
if (req != null)
{
try
{
//we call the success callback as long as we get a response stream
WebResponse response = req.EndGetResponse(final_result);
success_callback(response.GetResponseStream());
}
catch (WebException e)
{
//otherwise call the error/failure callback
error_callback(e.Message);
return;
}
}
}, preq);
}
}, request);
}
I have a REST Service that accepts a id in the URL for PUT requests. So far the PUT request looks like this:
string url = "http://localhost:3596/WidgetManager.svc/Widgets/" + TextBox3.Text;
WebRequest req = WebRequest.Create(url);
req.Method = "PUT";
using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(resp.GetResponseStream());
Label4.Text = reader.ReadToEnd();
}
But I also need to send a Widget object in my request.
Widget w = new Widget();
w.Name = "worked!!!";
w.CogCount = 1000;
w.SprocketSize = 2000;
I saw a lot of examples on how to send strings. But what about objects like this?
You could serialise it using XML or JSON.
If it is such a small object, you could write your own small method like
.toJSON() {
return '{"Name":"' + this.name + '", "CogCount":' + this.CogCount + ', "SprocketSize":' + this.SprocketSize + '}';
}
//Output: '{"Name":"worked!!!", "CogCount":1000, "SprocketSize":2000}'
On the other hand: C# provides powerful (XML) serialisation tools!
This here: http://www.codeproject.com/Articles/1789/Object-Serialization-using-C is only one of many examples.
But if you use PHP or similar, JSON might even be more interesting.
Sorry for virtually begging for help here but I've been tasked to work on the above and cannot find any adequate resources to help me. Here's the details:
The company has Identity management software which provides an SPML (SOAP) 'feed' of changes to user entitities
(If I've got this right) the SPML driver makes a POST request to a URL on my server which sends those changes
Whatever sits under that URL has to then process the posted information (XML)
Point 3 is my bit. I have no idea what to write. Asmx? Aspx? Ashx? Commodore 64 cassette tape? Apparently the SPML driver needs a 200 response - it will get that anyway when the processing has taking place no? Is there anything more to it that I'm not getting?
Any help, pointers, guidance or advising me to give up and get a new hobby, would be much appreciated.
Thanks.
EDIT..............
Have got a simple soap driver going (for the purposes of testing) which posts xml to an aspx page which then, in turn, consumes the POST and saves the xml. Thanks to J Benjamin (below) and http://www.eggheadcafe.com/articles/20011103.asp for the kick-start.
SOAP DRIVER (works on page load)
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(MySite.FileRoot + "testing\\testxml.xml");
HttpWebRequest req =
(HttpWebRequest)WebRequest.Create("http://localhost/mysite/testing/reader.aspx");
req.ContentType = "text/xml; charset=\"utf-8\"";
req.Method = "POST";
req.Headers.Add("SOAPAction", "\"\"");
Stream stm = req.GetRequestStream();
doc.Save(stm);
stm.Close();
WebResponse resp = req.GetResponse();
stm = resp.GetResponseStream();
StreamReader r = new StreamReader(stm);
Response.Write(r.ReadToEnd());
}
SOAP READER (reads xml posted when called)
protected void Page_Load(object sender, EventArgs e)
{
String Folderpath = "c:\\TestSOAP\\";
if (!Directory.Exists(Folderpath))
{
Directory.CreateDirectory(Folderpath);
}
Response.ContentType = "text/xml";
StreamReader reader = new StreamReader(Request.InputStream);
String xmlData = reader.ReadToEnd();
String FilePath = Folderpath + DateTime.Now.ToFileTimeUtc() + ".xml";
File.WriteAllText(FilePath, xmlData);
}
The next step is to try consume the SPML service (which is a Java-driven Novell type thing) - if I have any problems, I will post back here!!
Thanks all.. :)
Maybe I'm misunderstanding, but this sounds similar to how I'm handling URLs in my web service. We're handling logic based on URLs, do the logic, wrap it up in XML and respond with the XML object. Here's a simple example (by simple, I mean one of the few that doesn't require authentication)
The code below simply returns an XML object containing an AppSetting. The XML response is below as well (with some identifying values removed).
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "External/Application/{ApplicationGUID}/APIHost/")]
public Response GetAPIHostName(Request request, string ApplicationGUID)
{
Response response = new Response();
try
{
APIHost apiHost = new APIHost
{
APIHostname = System.Configuration.ConfigurationManager.AppSettings["PlayerAPIHostname"]
};
response.ResponseBody.APIHost = apiHost;
response.ResponseHeader.UMResponseCode = (int) UMResponseCodes.OK;
}
catch (GUIDNotFoundException guidEx)
{
response.ResponseHeader.UMResponseCode = (int)UMResponseCodes.NotFound;
response.ResponseHeader.UMResponseCodeDetail = guidEx.Message;
}
catch (Exception ex)
{
UMMessageManager.SetExceptionDetails(request, response, ex);
if (request != null)
Logger.Log(HttpContext.Current, request.ToString(), ex);
else
Logger.Log(HttpContext.Current, "No Request!", ex);
}
response.ResponseHeader.HTTPResponseCode = HttpContext.Current.Response.StatusCode;
return response;
}
/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
200
200
localhost