c# Display web request response in a panel - c#

1
Hi so I want to display the response of the website in this panel, How would I go about that. I have the necessary System.Net Etc. Heres the code:
private void panel7_Paint(object sender, PaintEventArgs e)
{
WebRequest request = WebRequest.Create("http://www.contoso.com/default.html");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
}
Would I need to set the webresponse as a string and than pass it as string tx?
[The code of said panel]
the code of the panel in cs
[3]: https://i.stack.imgur.com/DBY9w.png //the panel I want the data to display.

I believe you need a label in the panel, then change its label.Text property to the response body.
To read the response body from an HttpWebResponse, please refer to this answer.
I'd also suggest you switch to the modern HttpClient API if you use .NET Core 3 or above:
using var httpClient = new HttpClient();
Example:
using var httpRequest = new HttpRequestMessage(HttpMethod.Get, "http://www.contoso.com/default.html");
using var httpResponse = await httpClient.SendAsync(httpRequest);
label.Text = await httpResponse.Content.ReadAsStringAsync();
Or even simpler, if you don't need to edit the request message at all:
label.Text = await httpClient.GetStringAsync("http://www.contoso.com/default.html");

Related

Check whether a web URL is working or not in selenium

i'm trying to create a selenium script in c# to check whether a URL is working or returning any error. What is the simplest way to do that.
Don't do it with Selenium, use HttpClient
string url = "url";
var client = new HttpClient();
var checkingResponse = await client.GetAsync(url);
if (checkingResponse.IsSuccessStatusCode) {
Console.WriteLine($"{url} is alive");
}
To check whether a URL is working or returning any error using Selenium's C# clients, you can simply use WebRequest and HttpWebResponse class to get the page response and status code as follows:
//Declare Webrequest
HttpWebRequest re = null;
re = (HttpWebRequest)WebRequest.Create(url);
try
{
var response = (HttpWebResponse)re.GetResponse();
System.Console.WriteLine($"URL: {url.GetAttribute("href")} status is :{response.StatusCode}");
}
catch (WebException e)
{
var errorResponse = (HttpWebResponse)e.Response;
System.Console.WriteLine($"URL: {url.GetAttribute("href")} status is :{errorResponse.StatusCode}");
}

How to Get Data From PHP C#

I have a Php Script in my Host Which has the link of my new version of my Program,How Can I Get that link From Php? I mean I wanna get that link From Php and Save it in one String.
I Often Use This Code For Doing Something like this:
webbrowser.Nagative("MyPhp Uri");
webbrowser.Document.ExecCommand("SelectAll", false, null);
webbrowser.Document.ExecCommand("Copy", false, null);
Than I Paste it in one Textbox
textbox1.Paste();
But This Way is not Complete way to get data From Php?
Can you help me?
You should use webrequest instead.
I'm not posting a complete solution because I'm pretty sure you will find one as soon as you know what to search for:
using System;
using System.Net;
//create a request object and server call
Uri requestUri = new Uri("MyPhp Uri");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.requestUri);
//set all properties you need for the request, like
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(ProcessResponse), request);
//handle response
private void ProcessResponse(IAsyncResult asynchronousResult)
{
string responseData = string.Empty;
HttpWebRequest myrequest = (HttpWebRequest)asynchronousResult.AsyncState;
using (HttpWebResponse response = (HttpWebResponse)myrequest.EndGetResponse(asynchronousResult))
{
Stream responseStream = response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
responseData = reader.ReadToEnd();
}
responseStream.Close();
}
//TODO: do something with your responseData
}
Please notice: you should definitively add some try/catch blocks.. this is only a short example to point you in the right direction.

How to wait for a server to successfully respond to an HTTP request

I am currently working with an internal API and visual studio (new to both of them). I am trying to submit a GET request to the server which will give me a JSON with the user info. One of the field in the expected JSON response is connect_status which shows true if its connecting and false once the connection is done meaning the response has been received. So far I have been working with the following using Sleep to wait for a bit until getting the response.
bool isConnected;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost");
request.Method = WebRequestMethods.Http.Get;
request.ContentType = "application/json";
System.Threading.Thread.Sleep(10000);
do
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader info = new StreamReader(receiveStream);
string json = info.ReadToEnd();
accountInfo user1 = JsonConvert.DeserializeObject<accountInfo>(json);
Console.WriteLine(jsonResponse);
isConnected = user1.connect_status;
}
while (isConnected == true);
The problem with this is that I have to wait for a longer time, the time it takes is variable and that's why I have to set a higher sleep time. Alsosomeimtes 10 seconds might not be enough and in that case when the do while loop loops the second time I get an exception at while(isConnected==true) saying
NUllReferenceException was unhandled. Object reference not set to an
instance of an object.
What would be a better/different way of doing this as I don't think the way I am doing is right.
One option here, if using .NET 4.5:
HttpMessageHandler handler = new HttpClientHandler { CookieContainer = yourCookieContainer };
HttpClient client = new HttpClient(handler) {
BaseAddress = new Uri("http://localhost")
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpContent content = new StringContent("dataForTheServerIfAny");
HttpResponseMessage response = await client.GetAsync("relativeActionUri", content);
string json = await response.Content.ReadAsStringAsync();
accountInfo user1 = JsonConvert.DeserializeObject<accountInfo>(json);
This way you let .NET take care of that waiting and such for you.

Asp.Net c# logging in to another website

I know this question has been asked quite a lot of times which is how I have got to where I am at with the code below however I just can't get it to work on the particular website I am trying to access. At the site I am trying to access I need to retrieve certain values from the page however things like price and availability only come up after logging in so I am trying to submit my login information and then go to the product page to get the information I need using HTML Agility Pack.
At the moment it seems to attempt the login however the website is either not accepting it or the cookies are not present on the next page load to actually keep me logged in.
If someone could help me with this I would be very grateful as I am not a programmer but have been assigned this task as part of a software installation.
protected void Button5_Click(object sender, System.EventArgs e)
{
string LOGIN_URL = "http://www.videor.com/quicklogin/1/0/0/0/index.html";
string SECRET_PAGE_URL = "http://www.videor.com/item/47/32/0/703/index.html?scriptMode=&CUSTOMERNO=xxx&USERNAME=xxx&activeTabId=0";
// have a cookie container ready to receive the forms auth cookie
CookieContainer cookies = new CookieContainer();
// first, request the login form to get the viewstate value
HttpWebRequest webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
webRequest.CookieContainer = cookies;
StreamReader responseReader = new StreamReader(
webRequest.GetResponse().GetResponseStream()
);
string responseData = responseReader.ReadToEnd();
responseReader.Close();
string postData = "CUSTOMERNO=xxxx&USERNAME=xxxxx&PASSWORD=xxxxx";
// now post to the login form
webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.CookieContainer = cookies;
// write the form values into the request message
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postData);
requestWriter.Close();
// we don't need the contents of the response, just the cookie it issues
webRequest.GetResponse().Close();
// now we can send out cookie along with a request for the protected page
webRequest = WebRequest.Create(SECRET_PAGE_URL) as HttpWebRequest;
webRequest.CookieContainer = cookies;
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
// and read the response
responseData = responseReader.ReadToEnd();
responseReader.Close();
Response.Write(responseData);
}
This isn't a direct answer since I'm not sure what's wrong with your code (from a cursory glance it looks ok), but another approach is to use browser automation using Selenium . The following code will actually load the page using Chrome (you can swap out Firefox or IE) and is simpler to code against. It also won't break if they add javascript or something.
var driver = new ChromeDriver();
driver.Navigate().GoToUrl(LOGON_URL);
driver.FindElement(By.Id("UserName")).SendKeys("myuser");
driver.FindElement(By.Id("Password")).SendKeys("mypassword");
driver.FindElement(By.TagName("Form")).Submit();
driver.Navigate().GoToUrl(SECRET_PAGE_URL);
// And now the html can be found as driver.PageSource. You can also look for
// different elements and get their inner text and stuff as well.

Web Requests in C# for SilverLight 2.0

I have been using the following code to obtain a simple web response from Apache 2.2 in SilverLight to no avail.
private void bDoIt_Click(object sender, RoutedEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("/silverlight/TestPage2.html"));
request.Method = "POST";
request.ContentType = "text/xml";
request.BeginGetRequestStream(new AsyncCallback(RequestProceed), request);
}
private void RequestProceed(IAsyncResult asuncResult)
{
HttpWebRequest request = (HttpWebRequest)asuncResult.AsyncState;
StreamWriter postDataWriter = new StreamWriter(request.EndGetRequestStream(asuncResult));
postDataWriter.Close();
request.BeginGetResponse(new AsyncCallback(ResponceProceed), request);
}
private void ResponceProceed(IAsyncResult asuncResult)
{
HttpWebRequest request = (HttpWebRequest)asuncResult.AsyncState;
HttpWebResponse responce = (HttpWebResponse)request.EndGetResponse(asuncResult);
StreamReader responceReader = new StreamReader(responce.GetResponseStream());
string responceString = responceReader.ReadToEnd();
txtData.Text = responceString;
}
Does anyone no a better method of doing this?
Have you tried WebClient? This exists on silverlight, and might make life easier. Presumably you'd want UploadStringAsync.
Also - I believe you need to use and absolute url; if you don't want to hard code (quite reasonably), you can get your host from:
string url = App.Current.Host.Source.AbsoluteUri;
Then use string / etc methods to make the correct "http://yoursite/whatever/your.page";
Note that silverlight only allows (IIRC) connections to the host site.
You can do the BeginGetResponse call as the first call in your sample test case, the BeginGetRequestStream call is only needed if you are intending to pass some POST data to the requested page.

Categories