c# http post get
The provided code snippet and description detail a custom `WebClient` implementation in C#. This class is designed to handle HTTP requests and responses, specifically focusing on GET and POST methods. It also includes advanced functionalities such as uploading files and handling progress events during uploads and downloads. ### Key Features 1. **Handling HTTP GET and POST Requests:** - The class provides methods to send both GET and POST requests to a server. - For GET requests, the `OpenRead` method is used, which can accept a URL and return the response text or stream. - For POST requests, the `OpenRead` method can also be used with an additional parameter for the data to be posted. 2. **Uploading Files:** - The `UploadFile` method is used to upload files to a server. - It supports sending both text fields and file fields as part of the request. - Progress events can be raised during the upload process. 3. **Downloading Data:** - Files can be downloaded from a server using the `DownloadFile` method, which saves the file to a specified path. - Data streams can also be downloaded and saved to a memory stream using the `DownloadData` method. - Progress events can be raised during the download process. 4. **Handling HTTPS Connections:** - The class includes a method `OpenReadWithHttps` that handles HTTPS connections and resolves certificate issues by using a custom certificate policy. 5. **Custom Events for Uploads and Downloads:** - Custom delegates (`WebClientUploadEvent` and `WebClientDownloadEvent`) are defined to handle upload and download progress events. - Structs `UploadEventArgs` and `DownloadEventArgs` encapsulate data related to the progress of these operations. 6. **Advanced Functionality:** - The class supports setting various HTTP headers, including custom headers for requests. - It also manages cookies, allowing the user to set and retrieve cookies for the requests. - The `StatusCode` property provides access to the HTTP status code returned by the server. ### Usage Examples #### Basic Usage ```csharp HttpProc.WebClient client = new HttpProc.WebClient(); client.Encoding = System.Text.Encoding.Default; string responseText = client.OpenRead("http://example.com"); Console.WriteLine(responseText); ``` #### Downloading a File ```csharp client.DownloadFile("http://example.com/file.zip", @"C:\Downloads\file.zip"); ``` #### Uploading a File ```csharp string response = client.UploadFile("http://example.com/upload", "file1=C:\\upload\\file.txt"); Console.WriteLine(response); ``` #### Handling Progress Events ```csharp client.UploadProgressChanged += (sender, e) => { Console.WriteLine($"Uploaded {e.bytesSent}/{e.totalBytes} ({e.sendProgress * 100}% complete)"); }; client.DownloadProgressChanged += (sender, e) => { Console.WriteLine($"Downloaded {e.bytesReceived}/{e.totalBytes} ({e.ReceiveProgress * 100}% complete)"); }; ``` ### Advanced Usage #### Sending POST Data ```csharp string postData = "username=john&password=demo"; string response = client.OpenRead("http://example.com/login", postData); Console.WriteLine(response); ``` #### Handling HTTPS Connections ```csharp string secureResponse = client.OpenReadWithHttps("https://secure.example.com", "data=sensitive"); Console.WriteLine(secureResponse); ``` ### Additional Notes - The class handles connection management, including opening and closing TCP connections. - It provides methods to cancel ongoing operations (`Cancel` and `Start`). - The class supports setting and retrieving the encoding used for requests and responses. This custom `WebClient` implementation offers a comprehensive solution for handling HTTP requests and responses in C#, making it suitable for various web-based applications.
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using RE = System.Text.RegularExpressions.Regex;
using System.Security.Cryptography.X509Certificates;
/***************************************************************************************************************************************************
* *文件名:HttpProc.cs
* *创建人:HeDaode
* *日 期:2007.09.01
* *描 述:实现HTTP协议中的GET、POST请求
* *使 用:HttpProc.WebClient client = new HttpProc.WebClient();
client.Encoding = System.Text.Encoding.Default;//默认编码方式,根据需要设置其他类型
client.OpenRead("http://www.baidu.com");//普通get请求
MessageBox.Show(client.RespHtml);//获取返回的网页源代码
client.DownloadFile("http://www.codepub.com/upload/163album.rar",@"C:\163album.rar");//下载文件
client.OpenRead("http://passport.baidu.com/?login","username=zhangsan&password=123456");//提交表单,此处是登录百度的示例
client.UploadFile("http://hiup.baidu.com/zhangsan/upload", @"file1=D:\1.mp3");//上传文件
client.UploadFile("http://hiup.baidu.com/zhangsan/upload", "folder=myfolder&size=4003550",@"file1=D:\1.mp3");//提交含文本域和文件域的表单
*****************************************************************************************************************************************************/
namespace HttpProc
{
///<summary>
///上传事件委托
///<param name="sender"></param>
///<param name="e"></param>
public delegate void WebClientUploadEvent(object sender, HttpProc.UploadEventArgs e);
///<summary>
///下载事件委托
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
public delegate void WebClientDownloadEvent(object sender, HttpProc.DownloadEventArgs e);
///<summary>
///上传事件参数
///</summary>
public struct UploadEventArgs
{
///<summary>
///上传数据总大小
///</summary>
public long totalBytes;
///<summary>
///已发数据大小
///</summary>
public long bytesSent;
///<summary>
///发送进度(0-1)
///</summary>
public double sendProgress;
剩余25页未读,继续阅读
- 粉丝: 0
- 资源: 4
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
- 1
- 2
- 3
前往页