Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Program Cs

The document contains code for making HTTP requests using different methods in C#. It defines functions that make asynchronous and synchronous requests using HttpClient, WebRequest, and WebClient. The functions handle different error cases and return the response.

Uploaded by

Slime UNICORN
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Program Cs

The document contains code for making HTTP requests using different methods in C#. It defines functions that make asynchronous and synchronous requests using HttpClient, WebRequest, and WebClient. The functions handle different error cases and return the response.

Uploaded by

Slime UNICORN
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

using System;

using System.Diagnostics;
using System.Net;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Text.Json;
using System.Text;
using static System.Net.Mime.MediaTypeNames;

namespace HTTPConnection_example_01
{
internal class Program
{
static void Main(string[] args)
{
string s = MyHttpConnectionAsync("http://www.google.com/").Result;
Console.WriteLine(" ");
Console.WriteLine(" ");
Console.WriteLine(" Response " + s);
//string s = MyHttpConnectionSync("http://www.google.com/");
//Console.WriteLine(" Response " + s);
}
static async Task<string> MyHttpConnectionAsync(string url) {
string response = "";
string content="";
string title;
HttpClient MyHttpClient = new HttpClient();
Uri myuri = new Uri(url);
MyHttpClient.BaseAddress = myuri;
try {
var httpresponse = await MyHttpClient.GetAsync(myuri);
content = await httpresponse.Content.ReadAsStringAsync();
Console.WriteLine("Content " + httpresponse.Content);
Console.WriteLine("StatusCode " + httpresponse.StatusCode);
Console.WriteLine("Headers " + httpresponse.Headers);
Console.WriteLine(httpresponse.EnsureSuccessStatusCode());
Console.WriteLine("Content" + content);
response = content;
}
catch (TaskCanceledException tex) { Debug.WriteLine(tex.Message); }
catch (InvalidOperationException iex) { Debug.WriteLine(iex.Message); }
catch (HttpRequestException rex) { Debug.WriteLine(rex.Message); }
catch (Exception ex) { Debug.WriteLine(ex.Message); }
// Parse the content of the response to extract the fields you want
// Here's an example of extracting the title of the page:
var titleStartTag = "<title>";
var titleEndTag = "</title>";
var titleStartIndex = content.IndexOf(titleStartTag);
var titleEndIndex = content.IndexOf(titleEndTag,
titleStartIndex + titleStartTag.Length);
var titleLength = titleEndIndex - (titleStartIndex +
titleStartTag.Length);
title = content.Substring(titleStartIndex + titleStartTag.Length,
titleLength);
// Render the extracted fields into plaintext
Console.WriteLine($"Title: {title}");
return response;
}
static string MyWebrequestConnectionSync(string url) {
// Create a request for the URL.
WebRequest request = WebRequest.Create(url);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}

static string MyHttpConnectionSync(string url)


{
String response = "";
WebClient MyWebClient = new WebClient();
try
{
using Stream data = MyWebClient.OpenRead(url);
using StreamReader reader = new StreamReader(data);
response = reader.ReadToEnd();
}
catch (WebException tex) { Debug.WriteLine(tex.Message); }
catch (ArgumentNullException aex) { Debug.WriteLine(aex.Message); }
catch (IOException ioex) { Debug.WriteLine(ioex.Message); }
catch (ArgumentException arex) { Debug.WriteLine(arex.Message); }
return response;
}

//MyWebClient.Encoding = Encoding.UTF8;
//MyWebClient.Headers.Set(HttpRequestHeader.ContentType,
"application/json");
//MyWebClient.Headers.Add("user_key", key);
//MyWebClient.Headers.Add("Session_key", sessiosn);
//string json = JsonSerializer.Serialize(text);
//string serverResponse = MyWebClient.UploadString(url + "sms", "POST",
json);

static async Task<string> HttpConnectionClientMethod(string url)


{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
string pagecontent = "";
try
{
var response = await client.GetAsync(client.BaseAddress);
pagecontent = await response.Content.ReadAsStringAsync();
}
catch (TaskCanceledException tex) { Debug.WriteLine(tex.Message); }
catch (InvalidOperationException iex) { Debug.WriteLine(iex.Message); }
catch (HttpRequestException rex) { Debug.WriteLine(rex.Message); }
catch (Exception ex) { Debug.WriteLine(ex.Message); }

return pagecontent;
}
}
}

You might also like