Getting error when compiled Http webrequest - c#

i have written a program to search value from google every thing works fine but first time when page is loaded then i encounter error.after words if i click any link it is working fine no errors further.
Code is as follow
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string raw = "http://www.google.com/search?hl=en&q={0}&aq=f&oq=&aqi=n1g10";
string search = string.Format(raw, HttpUtility.UrlEncode(searchTerm));
//string search = "http://www.whatismyip.com/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
{
browserA = reader.ReadToEnd();
this.Invoke(new EventHandler(IE1));
}
}
}

This error didn't come from Http webrequest,it's from the web browser control on your form.
It's a javascript error raised by web browser control,you can suppress it by:
webBrowser.ScriptErrorsSuppressed = true;

Disable Internet Explorer notification for script errors
see http://www.tech-faq.com/internet-explorer-script-error.html

Related

How to get the dynamic data of websites which has ajax calls in c#

Sorry if my question was not in proper manner do edit if required.
USE CASE
I want a function which will find the given string or text from a web page as soon as it updated in wepage in c#.
Take example as https://www.worldometers.info/world-population/ i am trying to get "40" data.So,when the current page will load "40" data or content my function should stop.I think its not loading the AJAX calls.
public static void WaitForWebPageContent(string url,string text)
{
while (true)
{
string pageContent = null;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();
using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
pageContent = sr.ReadToEnd();
}
if(pageContent.Contains(text))
{
Debug.WriteLine("Found it");
break;
}
}
}
My Question
I am searching for a method where i can get the page content by calling it from my function.Currently i am using httpclient to get the response from a URL but the data its not stopping even the content is loaded in browser.I am continously sending the request in each and every second by using the above code.Please guide me to proper solution
Thanks

Webbrowser control not displaying web pages correctly

am trying to use webbrowser control in my windows form application to display web pages like youtube, BBC etc. Am seeing that in some of the sites the CSS is totally out of place and scripts are not being executed. Can some help me resolve this. Also is there any possible method with which i can open IE in kiosk mode inside and windows form?
Below is the code that am currently using to launch my sites.
private void browser_Load(object sender, EventArgs e)
{
this.ControlBox = false;
this.WindowState = FormWindowState.Maximized;
toolStripButton1.Text = etext;
toolStripLabel1.Text = webnamedisplayname;
browser.ScriptErrorsSuppressed = true;
browser.Navigate(NavUrl);
}
After years of using the WebBrowser Control I never had a problem until recently! In my case, I was being served a Mobile version of the Pages I was requesting! A real pain, all due to a little app called: "Mobvious"
I managed to get around this issue by using the following code:
private void GetWebPage()
{
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(this.AddressTextBox.Text);
Request.Method = "GET";
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
string Server = Response.Server;
HttpStatusCode StatusCode = Response.StatusCode;
if (StatusCode == HttpStatusCode.OK)
{
Stream ResponseStream = Response.GetResponseStream();
StreamReader Reader = new StreamReader(ResponseStream);
this.webBrowser1.DocumentText = Reader.ReadToEnd();
}
else
{
this.BadURI = this.BadURI + 1;
}
}

Windows phone 8 dev: HttpWebRequest.BeginGetResponse callback never called

I'm starting windows phone 8 development on my Windows 8 machine and test on the emulator that comes with visual studio 2012. I have a main page with one button on it. Upon pressing the button, it makes a http request.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string uriString = "http://209.143.33.109/mjpg/video.mjpg?camera=1";
var uri = new Uri(uriString);
var httpWebRequest = HttpWebRequest.Create(uri);
httpWebRequest.BeginGetResponse(new AsyncCallback(OnGettingResponse), httpWebRequest);
}
private void OnGettingResponse(IAsyncResult ar)
{
var req = ar.AsyncState as HttpWebRequest;
var response = (HttpWebResponse)req.EndGetResponse(ar);
var responseStream = response.GetResponseStream();
}
I set a breakpoint on OnGettingResponse. But when I press the button, the breakpoint is never hit.
Am I missing anything obvious here?
I was facing the same issue that my callback was not being called even after waiting too long.
I found this stackoverflow answer https://stackoverflow.com/a/15041383 and modified my code accordingly. The actual problem in that question was that asker wants to have some timeout functionality in the HttpWebRequest under Windows Phone 8. Having timer was irrelevant for me, so I just took the following part of code:
public async Task<string> httpRequest(HttpWebRequest request)
{
string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
received = await sr.ReadToEndAsync();
}
}
}
return received;
}
and modified my call to this method as:
var response = await httpRequest(request);
This is now working fine for me.
I also double checked that ID_CAP_NETWORKING is check in WMAppManifest.xml and internet is working on my emulator.

Connect to website with Windows Phone 7

I'm developing a project for windows phone 7. It's very simple I guess but I don't know very well C# especially C# for wp7.
I have an existing php page with this code
<?php
if(isset($_GET['name'])) {
$ssid=$_GET['name'];
}
$name .= "Hello";
?>
I want to make a wp7 application where I can write a name in text, press the button to connect to server, pass the name in the text as php parameter and write server response in another text on mobile screen. How can I do this?
Something like this perhaps?
POST Request
Try this (read the first comment tho... author made a typo):
Post Request
Create an HttpWebRequest with your query :
private void MyMethod(Action action){
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(string.Format("http://website/page.php?name={0}",name));
webRequest.BeginGetResponse((callBack)=>{
HttpWebRequest request = (HttpWebRequest)callBack.AsyncState;
WebResponse webResponse = request.EndGetResponse(callBack);
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
{
string response = string.Empty;
try
{
response = sr.ReadToEnd();
}
catch (Exception ex)
{
response = ex.Message;
}
action.Invoke(response);
}
webResponse.Close();
},webRequest)
}
where textresponse is your server response
Try this one, it helps you
in first page or form,
NavigationService.Navigate(new Uri("/Projectname;component/pagename.xaml?name=" + variable1 + "&country="+variable2, UriKind.Relative));
in second page or form,
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string myname = NavigationContext.QueryString["name"];
string Mycountry = int.Parse(NavigationContext.QueryString["country"]);
}
The 'name' and 'country' in OnNavigatedTo are same as navigateservice
In this way you send values from one page to another page.

JSON Data posted by Silverlight is not reaching the server

I have a web client I'm creating in Silverlight. I am trying to get it to communicate it with my web services on my server through GET and POST requests and JSON. The GET requests work fine and I'm able to parse the JSON on the Silverlight end. The POST requests however dont seem to work. The server reads that there is a POST request, but the POST array is empty.
Ive tried two pieces of code to send the POST requests, but both are resulting in the same response - an empty array.
The first Silverlight code I tried was:
public MainPage()
{
InitializeComponent();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://www.dipzo.com/game/services.php"));
request.Method = "POST";
request.ContentType = "application/json";
request.BeginGetRequestStream(new AsyncCallback(OnGetRequestStreamCompleted), request);
}
private void OnGetRequestStreamCompleted(IAsyncResult ar)
{
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
using (StreamWriter writer = new StreamWriter(request.EndGetRequestStream(ar)))
{
writer.Write("name=david");
}
request.BeginGetResponse(new AsyncCallback(OnGetResponseCompleted), request);
}
private void OnGetResponseCompleted(IAsyncResult ar)
{
//this.GetResponseCoimpleted.Visibility = Visibility.Visible;
// Complete the Flickr request and marshal to the UI thread
using (HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)ar.AsyncState).EndGetResponse(ar))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string results = reader.ReadToEnd();
}
}
}
The second piece I tried was:
private void WebClient_Click(object sender, RoutedEventArgs e)
{
Test t1 = new Test() { Name = "Civics", Marks = 100 };
DataContractJsonSerializer jsondata = new DataContractJsonSerializer(typeof(Test));
MemoryStream mem = new MemoryStream();
jsondata.WriteObject(mem, t1);
string josnserdata = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient cnt = new WebClient();
cnt.UploadStringCompleted += new UploadStringCompletedEventHandler(cnt_UploadStringCompleted);
cnt.Headers["Content-type"] = "application/json";
cnt.Encoding = Encoding.UTF8;
cnt.UploadStringAsync(new Uri("http://www.dipzo.com/game/services.php"), "POST", josnserdata);
}
void cnt_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
var x = e;
}
The code on the server to consume the service is in PHP and is essentially:
var_dump($_POST)
This should output whatever is coming into the post array. I've tested it with a simple PHP client and it works. Just can't get it to work in silverlight. In silverlight I just keep getting an empty array.
You should change the Content-type to application/x-www-form-urlencoded and not application/json which is not a known type yet.
Not that I think anyone is still paying attention tot his old question, but I'm betting that the problem was that it actually WAS getting to the server, but that the server routed the result back to the SL application. This is the behavior I'm seeing with a similar situation from SL5 usingWebClient.UploadStringAsync.
I'm about to implement/test a technique I ran across yesterday which uses a dynamically built, "real" page post from SL; I'll report my findings shortly.
UPDATE -- THIS SOLUTION WORKS:
http://www.codeproject.com/Tips/392435/Using-HTTP-Form-POST-method-to-pass-parameters-fro
I've just tested it in my application (SL5 inside MVC) and it works just fine. Make sure you check the HttpContext.Request.Form["fieldname"] to get the value(s) that you want. I used this technique to submit JSON and was able to return a generated Word document for the user.
Once I implemented this I was able to get rid of the unnecessary WebClient that I was attempting to use before.

Categories

Resources