httpwebresponse and encoding in silverlight - c#

How to get httpWebresponse in silverlight?
there is not method getResponse so this code doesn't work
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
And how to change this
...new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding(1251)))
I've got error on 1251. What name of the encoding?

For the first one: you need to use the asynchronous version, since there are no synchronous networking calls in SL.
public void Button_Click(object sender, EventArgs e)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "GET";
req.BeginGetResponse(HWRCallback, req);
}
void HWRCallback(IAsyncResult ar)
{
HttpWebRequest req = (HttpWebRequest)ar.AsyncState;
HttpWebResponse resp = (HttpWebResponse)req.EndGetResponse(ar);
// use response
}
For the second (by the way, consider asking two questions next time), maybe that encoding isn't supported in Silverlight. Loop through the result of Encoding.GetEncodings() to see all the encodings which are available in that platform.

Consider using the WebClient Class and in particular the DownloadStringAsync Method:
var client = new WebClient();
client.DownloadStringCompleted += (sender, e) =>
{
string result = e.Result;
};
client.DownloadStringAsync(uri);
It makes it simpler to perform an HTTP request as an asynchronous operation than HttpWebRequest. (In Silverlight, HTTP requests are required to be asynchronous.) And it provides the result conveniently as string, taking care of all encoding issues that might arise. (The server usually tells the client which encoding to use.)

Related

Blocking asynchronous operation in Windows phone

I am trying send the http post from the windows phone to the server and I am getting some of problem via sending the post data.I put the break point in button_click_1 function and I found that it would not start the asynronous operation. Beside that, it also block the current thread and I know that this situation is cause by the allDone.waitOne().
Why the asynronous operation will not function and how to solve it?
Thank you for any help.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
// Create a new HttpWebRequest object.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
// start the asynchronous operation
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
allDone.WaitOne();
}
Asynronous operation:
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
string postData = "xxxxxxxxxxx";
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Write to the request stream.
postStream.Write(byteArray, 0, postData.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
tbtesting.Text = responseString.ToString();
streamResponse.Close();
streamRead.Close();
response.Close();
allDone.Set();
}
You're not the first to hit this (see Is it possible to make synchronous network call on ui thread in wpf (windows phone)). If you do this then you deadlock the UI thread on Windows Phone.
The closest you're going to get is to use the async/await on your network calls. There are extension methods you can use to do this as part of the Microsoft.Bcl.Async package on NuGet.

Alternative to this Http Request

I have a class that goes and grabs some data and returns it as a string. While this object is working there is a spinning icon letting the user know work is being done. The problem is the code exits before the response comes back. I stuck a
while(response == null)
In just to see whats going on and the
response = (HttpWebResponse)request.EndGetResponse(AsyncResult);
is not firing. It fires ok in a console application so I am putting this down to something I am doing that silverlight doesn't like, heres the full code:
public class HttpWorker
{
private HttpWebRequest request;
private HttpWebResponse response;
private string responseAsString;
private string url;
public HttpWorker()
{
}
public string ReadFromUrl(string Url)
{
url = Url;
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = new CookieContainer();
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
AsyncRequest(); // The Demon!
return responseAsString;
}
private void AsyncRequest()
{
request.BeginGetResponse(new AsyncCallback(FinaliseAsyncRequest), null);
}
private void FinaliseAsyncRequest(IAsyncResult AsyncResult)
{
response = (HttpWebResponse)request.EndGetResponse(AsyncResult);
if (response.StatusCode == HttpStatusCode.OK)
{
// Create the stream, encoder and reader.
Stream responseStream = response.GetResponseStream();
Encoding streamEncoder = Encoding.UTF8;
StreamReader responseReader = new StreamReader(responseStream, streamEncoder);
responseAsString = responseReader.ReadToEnd();
}
else
{
throw new Exception(String.Format("Response Not Valid {0}", response.StatusCode));
}
}
}
Are you going into the busy loop with (while response == null) on the UI thread? The async callback for the HttpRequest will be delivered on the UI thread, so if you're looping on that same thread, the callback can never run. You need to return to allow the main message loop to run, and then your async callback will be delivered.
Your design above suggests that what you really want is a synchronous fetch anyway. Forget the callback and just call FinaliseAsyncRequest inside ReadFromUrl yourself. The UI will hang until the request completes, but it sounds like that's what you want.
I posted a working sample here of using WebClient and HttpWebRequest.
WebClient, HttpWebRequest and the UI Thread on Windows Phone 7
Note the latter is preferred for any non trivial processing to avoid blocking the UI.
Feel free to reuse the code.
The easiest way to get a string from a web server is to use WebClient.DownloadStringAsync() (MSDN docs).
Try something like this:
private void DownloadString(string address)
{
WebClient client = new WebClient();
Uri uri = new Uri(address);
client.DownloadStringCompleted += DownloadStringCallback;
client.DownloadStringAsync(uri);
StartWaitAnimation();
}
private void DownloadStringCallback(object sender, DownloadStringCompletedEventArgs e)
{
// Do something with e.Result (which is the returned string)
StopWaitAnimation();
}
Note that the callback executes on the UI thread and so you should only use this method if your callback method is not doing very much as it will block the UI while it executes.
If you need more control over the web request then you can use HttpWebRequest.
If you really must imitate synchronous behaviour have a look at Faking synchronous calls in Silverlight WP7

Invoking a URL - c#

I m trying to invoke a URL in C#, I am just interested in invoking, and dont care about response. When i have the following, does it mean that I m invoking the URL?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
You need to actually perform the request:
var request = (HttpWebRequest)WebRequest.Create(url);
request.GetResponse();
The call to GetResponse makes the outbound call to the server. You can discard the response if you don't care about it.
First) Create WebRequest to execute URL.
Second) Use WebResponse to get response.
Finally) Use StreamReader to decode response and convert it to normal string.
string url = "Your request url";
WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseText = reader.ReadToEnd();
You can use this:
string address = "http://www.yoursite.com/page.aspx";
using (WebClient client = new WebClient())
{
client.DownloadString(address);
}
No when you say request.GetResponse(); then you invoke it.
Probably not. See: http://www.codeproject.com/KB/webservices/HttpWebRequest_Response.aspx
You're allowed to set the Method, ContentType, etc., all which would have to be done before the request is actually sent. It looks like GetResponse() actually sends the request. You can simply ignore the return value.

C# Check url exist?

How can I check whether a page exists at a given URL?
I have this code:
private void check(string path)
{
try
{
Uri uri = new Uri(path);
WebRequest request = WebRequest.Create(uri);
request.Timeout = 3000;
WebResponse response;
response = request.GetResponse();
}
catch(Exception loi) { MessageBox.Show(loi.Message); }
}
But that gives an error message about the proxy. :(
First, you need to understand that your question is at least twofold,
you must first check if the server is responsive, using ping for example - that's the first check, while doing this, consider timeout, for which timeout you will consider a page as not existing?
second, try retrieving the page using many methods which are available on google, again, you need to consider the timeout, if the server taking long to replay, the page might still "be there" but the server is just under tons of pressure.
If the proxy needs to authenticate you with your Windows credentials (e.g. you are in a corporate network) use:
WebRequest request=WebRequest.Create(url);
request.UseDefaultCredentials=true;
request.Proxy.Credentials=request.Credentials;
try
{
Uri uri = new Uri(path);
HttpWebRequest request = HttpWebRequest.Create(uri);
request.Timeout = 3000;
HttpWebResponse response;
response = request.GetResponse();
if (response.StatusCode.Equals(200))
{
// great - something is there
}
}
catch (Exception loi)
{
MessageBox.Show(loi.Message);
}
You can check the content-type and length, see MSDN HTTPWebResponse.
At a guess, without knowing the specific error message or path, you could try casting the WebRequest to a HttpWebRequest and then setting the WebProxy.
See MSDN: HttpWebRequest - Proxy Property

Communicating with the web through a C# app?

Although i can grasp the concepts of the .Net framework and windows apps, i want to create an app that will involve me simulating website clicks and getting data/response times from that page. I have not had any experience with web yet as im only a junior, could someone explain to me (in english!!) the basic concepts or with examples, the different ways and classes that could help me communicate with a website?
what do you want to do?
send a request and grab the response in a String so you can process?
HttpWebRequest and HttpWebResponse will work
if you need to connect through TCP/IP, FTP or other than HTTP then you need to use a more generic method
WebRequest and WebResponse
All the 4 methods above are in System.Net Namespace
If you want to build a Service in the web side that you can consume, then today and in .NET please choose and work with WCF (RESTfull style).
hope it helps you finding your way :)
as an example using the HttpWebRequest and HttpWebResponse, maybe some code will help you understand better.
case: send a response to a URL and get the response, it's like clicking in the URL and grab all the HTML code that will be there after the click:
private void btnSendRequest_Click(object sender, EventArgs e)
{
textBox1.Text = "";
try
{
String queryString = "user=myUser&pwd=myPassword&tel=+123456798&msg=My message";
byte[] requestByte = Encoding.Default.GetBytes(queryString);
// build our request
WebRequest webRequest = WebRequest.Create("http://www.sendFreeSMS.com/");
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.ContentLength = requestByte.Length;
// create our stram to send
Stream webDataStream = webRequest.GetRequestStream();
webDataStream.Write(requestByte, 0, requestByte.Length);
// get the response from our stream
WebResponse webResponse = webRequest.GetResponse();
webDataStream = webResponse.GetResponseStream();
// convert the result into a String
StreamReader webResponseSReader = new StreamReader(webDataStream);
String responseFromServer = webResponseSReader.ReadToEnd().Replace("\n", "").Replace("\t", "");
// close everything
webResponseSReader.Close();
webResponse.Close();
webDataStream.Close();
// You now have the HTML in the responseFromServer variable, use it :)
textBox1.Text = responseFromServer;
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}
}
The code does not work cause the URL is fictitious, but you get the idea. :)
You could use the System.Net.WebClient class of the .NET Framework. See the MSDN documentation here.
Simple example:
using System;
using System.Net;
using System.IO;
public class Test
{
public static void Main (string[] args)
{
if (args == null || args.Length == 0)
{
throw new ApplicationException ("Specify the URI of the resource to retrieve.");
}
WebClient client = new WebClient ();
// Add a user agent header in case the
// requested URI contains a query.
client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
Stream data = client.OpenRead (args[0]);
StreamReader reader = new StreamReader (data);
string s = reader.ReadToEnd ();
Console.WriteLine (s);
data.Close ();
reader.Close ();
}
}
There are other useful methods of the WebClient, which allow developers to download and save resources from a specified URI.
The DownloadFile() method for example will download and save a resource to a local file. The UploadFile() method uploads and saves a resource to a specified URI.
UPDATE:
WebClient is simpler to use than WebRequest. Normally you could stick to using just WebClient unless you need to manipulate requests/responses in an advanced way. See this article where both are used: http://odetocode.com/Articles/162.aspx

Categories

Resources