httpwebresponse and encoding in silverlight

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?

Upvotes: 0

Views: 215

Answers (2)

dtb
dtb

Reputation: 217233

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.)

Upvotes: 1

carlosfigueira
carlosfigueira

Reputation: 87218

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.

Upvotes: 1

Related Questions