I am trying to load web browser with the html code from the httpwebresponse by storing it in a string variable.
I created a httpwebrequest for a URL by setting cookies in it and getting a html page in a httpwebResponse.
I am trying to display it in a web browser control by saving the code in a string variable. And navigating the browser("browse.NavigateToString(string)").
But here page is not loaded properly.It is not displaying any css or images and displaying a message"You need to turn on java script in order to display the contents".
I made the web browser property (IsScriptEnabled ) true before navigation. But it is still showing the message and contents are not loaded properly.
Cookies are also not injected in to the web browser controls(session is not maintained through out the app).
Is there any solution or work around for this ??
Please refer to the below code :
To log cookies from login service :
private void PostLoginRequest()
{
string AuthServiceUri = "Service URL";
HttpWebRequest AuthReq = HttpWebRequest.Create(AuthServiceUri) as HttpWebRequest;
AuthReq.CookieContainer = new CookieContainer();
AuthReq.ContentType = "application/x-www-form-urlencoded";
AuthReq.Method = "POST";
AuthReq.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), AuthReq);
}
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest Request = (HttpWebRequest)callbackResult.AsyncState;
Stream postStream = Request.EndGetRequestStream(callbackResult);
string postData = "Postdata parameters";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), Request);
}
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
try
{
HttpWebRequest callBackRequest = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
CookieCollection cookiecollec = new CookieCollection();
cookiecollec = response.Cookies;
App.cookieCollection = cookiecollec; //global varaiable
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
Another httpwebrequest with logged cookies :
private void ResponsivePostURL(string PageName, string PostURL, string PostDatas)
{
Uri ServiceUri = new Uri(PostURL); //Service URL
HttpWebRequest requestURL = HttpWebRequest.CreateServiceUri as HttpWebRequest;
requestURL.ContentType = "application/x-www-form-urlencoded";
requestURL.Method = "POST";
requestURL.CookieContainer = new CookieContainer();
requestURL.CookieContainer.Add(ServiceUri, App.cookieCollection);
requestURL.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), requestURL);
}
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
// MessageBox.Show(response.Cookies.ToString());
string responseString = "<html><head></head><body>";
Stream streamResponse = response.GetResponseStream();
StreamReader reader = new StreamReader(streamResponse);
responseString = responseString + reader.ReadToEnd() + "</body></html>";
streamResponse.Close();
reader.Close();
response.Close();
this.Dispatcher.BeginInvoke(() =>
{
webBrowser.IsScriptEnabled = true;
webBrowser.NavigateToString(responseString);
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
When you navigate to the site and save the document, you are not getting the script, css nor image files (and any other resource for that matter) but only the static/generated HTML document as-is, which probably refer to those files using relative paths. If paths are not absolute, scripts/css/images/other resources are not found.
If you want to make it work, you need to replace relative paths with absolute paths within the HTML file.
So if you have
<script src="/scripts/cool.js"></script>
You'd replace it with
<script src="http://www.thesite.com/scripts/cool.js"></script>
(Note that this is just my best guess, not something I have actually tried out :)
Related
I have a WP7 app where I'm trying to reconstruct an HTTPWebRequest that I have successfully written elsewhere using the synchronous methods (pasted at end) but which doesn't work in WP7, I assume because I'm doing something wrong with the Asynchronous versions of these methods.
I believe the issue stems from the fact that the non-working code on the Compact Framework can only send a bytearray[] - I don't have the option of sending the json string. If I send a bytearray in the code that works, I get an error there too. Is there a different option?
Here is my code - this does not work. The exception is thrown on the 2nd line of the last method - "Using(var respons ...)":
public void CreateUser()
{
var request = (HttpWebRequest)WebRequest.Create("http://staging.cloudapp.net:8080/api/users/");
request.Method = "POST";
request.ContentType = "text/json; charset=utf-8";
request.BeginGetRequestStream(new AsyncCallback(RequestCallback), request);
}
private static void RequestCallback(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
using (Stream postStream = request.EndGetRequestStream(result))
{
User user = new User("Windows", "Phone", "USCA");
Formatting formatting = new Formatting();
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
string json = JsonConvert.SerializeObject(user, formatting, settings);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
postStream.Write(byteArray, 0, json.Length);
}
request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
}
private static void ResponseCallback(IAsyncResult result)
{
var request = (HttpWebRequest)result.AsyncState;
using (var response = (HttpWebResponse)request.EndGetResponse(result))
{
using (Stream streamResponse = response.GetResponseStream())
{
StreamReader reader = new StreamReader(streamResponse);
string responseString = reader.ReadToEnd();
reader.Close();
}
}
}
This code works (non-compact framework version of the same request):
HttpWebRequest request = HttpWebRequest.Create("http://staging.cloudapp.net/api/users/") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/json";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
User user = new user("Other", "Guy", "USWC");
Formatting formatting = new Formatting();
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
string json = JsonConvert.SerializeObject(user, formatting, settings);
writer.Write(json);
}
var response = request.GetResponse() as HttpWebResponse;
using (var reader = new StreamReader(response.GetResponseStream()))
{
var responseText = reader.ReadToEnd();
return responseText;
}
thanks for any help!
looks like the server is responding with a "404 not found". Does the resource you are requesting exist at the server?
Does your JSON contain any non 7-bit ASCII characters, as you are currently doing:
byte[] byteArray = Encoding.UTF8.GetBytes(json);
postStream.Write(byteArray, 0, json.Length);
The number of bytes might not be identical to the number of characters in your string, which could lead to a malformed request.
It would be worthwhile using something like Fiddler to verify what is actually going over the wire from the emulator or phone (there are instructions on the Fiddler website for how to do this)
Well - I'm not sure why this problem went away. I liked #RowlandShaw's suggestion, but I didn't actually change anything in the json. Wish I could give a better solution.
when i down load the two same link like those
a link! and http://files.sparklingclient.com/099_2010.07.09_WP7_Phones_In_The_Wild.mp3
they all can be downloded by IE .but when i download in wp7 the laster can be downloaded the first show an error ""The remote server returned an error: NotFound.""
i don't konw why .is webURL is not suited for wp7?
private void Button_Click(object sender, RoutedEventArgs e)
{
stringUri = "http://upload16.music.qzone.soso.com/30828161.mp3";
//stringUri = "http://files.sparklingclient.com/079_2009.08.20_ElementBinding.mp3";
Uri uri = new Uri(stringUri, UriKind.Absolute);
GetMusic(uri);
}
private void GetMusic(Uri uri)
{
request = WebRequest.Create(uri) as HttpWebRequest;
request.Method = "Post";
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
string header= request.Accept;
request.BeginGetResponse(new AsyncCallback(GetAsynResult),request);
}
void GetAsynResult(IAsyncResult result)
{
HttpWebResponse reponse = request.EndGetResponse(result) as HttpWebResponse;
if (reponse.StatusCode == HttpStatusCode.OK)
{
Stream stream=reponse.GetResponseStream();
SaveMusic(stream, "music");
ReadMusic("music");
Deployment.Current.Dispatcher.BeginInvoke(
() =>
{
me.AutoPlay = true;
me.Volume = 100;
songStream.Position = 0;
me.SetSource(songStream);
me.Play();
});
}
}
protected void SaveMusic(Stream stream,string name)
{
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (!fileStorage.DirectoryExists("Source/Music"))
{
fileStorage.CreateDirectory("Source/Music");
}
using (IsolatedStorageFileStream fileStream = IsolatedStorageFile.GetUserStoreForApplication().OpenFile("Source\\Music\\" + name + ".mp3", FileMode.Create))
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Flush();
}
}
protected void ReadMusic(string name)
{
using (IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
songStream = null;
songStream = new IsolatedStorageFileStream("Source\\Music\\" + name + ".mp3", FileMode.Open, fileStorage);
}
}
Please try to change
request.Method = "Post"
to
request.Method = "Get"
If you are running into this problem on the emulator, have you tried running Fiddler? It will intercept the HTTP requests and you can see if the call being made to the server is the one you expect.
Remember to close/reopen the emulator after you start Fiddler so that it will pick up the proxy.
The NotFound response can also occur with bad SSL certificates. That doesn't appear to be related to your problem, but something to keep in mind.
I need to use POST to post a string to server and get xml response, the status code is OK but the string reponse is always ="" (0 byte). Is there any thing wrong with my code? I check the server from blackberry, works fine so the problem must come from my code:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
s = NavigationContext.QueryString["parameter1"];
//string strConnectUrl = "http://www.contoso.com/example.aspx";
base.OnNavigatedTo(e);
// DoWebClient(s);
try
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(strConnectUrl);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
// start the asynchronous operation
httpWebRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), httpWebRequest);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
// string XML_REQUEST = "<?xml version=\"1.0\"?><mybroker"><getConnections></mybroker>";
string post = "?&track=love";
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);
// Convert the string into a byte array.
byte[] postBytes = Encoding.UTF8.GetBytes(post);
// Write to the request stream.
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
static Stream str;
static string st;
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
HttpStatusCode rcode = response.StatusCode;
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
//****THIS ALWAYS RETURN "" VALUE, EXPECT TO RETURN XML STRING****
string responseString = streamRead.ReadToEnd();
//Console.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
*EDIT**
The code work, however the server return parameter require the Ampersand(&) which is not allow in silverlight framework I think, remove the & char server response but the result wasn't correct. I will ask a new question refer this Ampersand
Have checked your call using Fiddler. The server is returning an empty body. Your code is working correctly. The problem is server side.
The post value should be "track=love".
I tried and it worked but the response is gzip encoded.
Fiddler says that the request is good, and that the response really is blank. If it's working from Blackberry and not from WP7, could the server be doing some user agent checking and not returning anything because it doesn't recognize the WP7 user agent?
Also, it looks like you're POSTing a query string ("?&track=love") which is sort of unusual. Are you sure that's the right data to be sending in your request?
cookie recieved from first request:
private void PostResponseCallback(IAsyncResult asyncResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
Stream content = response.GetResponseStream();
SESSIONID = response.Headers["Set-cookie"].ToString();
if (request != null && response != null)
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (StreamReader reader = new StreamReader(content))
{
string _responseString = reader.ReadToEnd();
ResponseString = _responseString;
reader.Close();
}
}
}
}
Unable to set cookie in second request
public void AccDetialsGetResponse()
{
try
{
//CookieContainer cc1 = new CookieContainer();
CookieCollection collection = new CookieCollection();
SESSIONID = SESSIONID.Replace("; Path=/", "");
Cookie cook = new Cookie();
cook.Name = "cookie";
cook.Value = SESSIONID;
collection.Add(cook);
//cc1.Add(new Uri(strHttpsUrl), cccs);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strHttpsUrl);
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(new Uri(strHttpsUrl), collection);
req.BeginGetRequestStream(AccDetailsPostRequest, req);
}
Kindly provide a solution to the above issue...
It turns out you are better off capturing the cookie store from the first request (like so)
//keep in mind ResponseAndCookies is just a hand rolled obj I used to hold both cookies and the html returned during the response
private ResponseAndCookies ReadResponse(IAsyncResult result)
{
Stream dataStream = null;
HttpWebRequest request = (HttpWebRequest) result.AsyncState;
HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse;
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
var responseAndCookies = new ResponseAndCookies
{CookieContainer = request.CookieContainer, Markup = responseFromServer};
return responseAndCookies;
}
And using this cookie store directly when you create then new request. (instead of manually adding the cookie like you had initially)
public void Checkout(ResponseAndCookies responseAndCookies)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/checkout");
request.ContentType = "application/json";
request.CookieContainer = responseAndCookies.CookieContainer;
request.Method = "POST";
request.AllowAutoRedirect = false;
request.Accept = "application/json";
request.BeginGetRequestStream(new AsyncCallback(GetRequest), request);
}
Note- if the cookies you are passing around are HTTP ONLY this is actually the ONLY way to deal with them (in the current release of windows phone 7)
I'm trying to send a request with the HttpWebRequest class on WP7, but I don't get any response...
Here is my code:
InitializeComponent();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
tbResponse.Text = reader.ReadToEnd();
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
Console.ReadLine();
Moreover, I use this extension: click here, but I tested it on a Windows Console Application and there wasn't any problem, so I think the problem is that I don't know something about WP7.
You need to make asynchronous requests like this:
var webRequest = (HttpWebRequest)HttpWebRequest.Create(Url);
webRequest.BeginGetResponse(new AsyncCallback(request_CallBack), webRequest );
and the response handler:
void request_CallBack(IAsyncResult result)
{
var webRequest = result.AsyncState as HttpWebRequest;
var response = (HttpWebResponse)WebRequest.EndGetResponse(result);
var baseStream = response.GetResponseStream();
// if you want to read binary response
using (var reader = new BinaryReader(baseStream))
{
DataBytes = reader.ReadBytes((int)baseStream.Length);
}
// if you want to read string response
using (var reader = new StreamReader(baseStream))
{
Result = reader.ReadToEnd();
}
}
Here is a helper class I developed to handle my web request needs during development of windows phone 7 apps:
http://www.manorey.net/mohblog/?p=17&preview=true