C#用httpclient模拟post到web网站上

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#用httpclient模拟post到web网站上相关的知识,希望对你有一定的参考价值。

客户端提供一个url,
模拟服务端 向这个url post数据(xml)流,
客户端从这个url接受

怎么实现啊

参考技术A 实例化下面的类,设置相关属性(url,method)等,调用call就好

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.IO;
using System.Net;
using System.Xml;
namespace xxxu

public class XXXUHttpClient

//请求内容,无论post和get,都用get方式提供
private string reqContent;
//应答内容
private string resContent;
//请求方法
private string method;
//错误信息
private string errInfo;
//证书文件
private string certFile;
//证书密码
private string certPasswd;
//ca证书文件
private string caFile;
//超时时间,以秒为单位
private int timeOut;
//http应答编码
private int responseCode;
//字符编码
private string charset;
public HuizeHttpClient()

this.caFile = "";
this.certFile = "";
this.certPasswd = "";
this.reqContent = "";
this.resContent = "";
this.method = "POST";
this.errInfo = "";
this.timeOut = 1 * 60;//5分钟
this.responseCode = 0;
setCharset(System.Web.HttpContext.Current.Request.ContentEncoding.BodyName);

//设置请求内容
public void setReqContent(string reqContent)

this.reqContent = reqContent;

//获取结果内容
public string getResContent()

return this.resContent;

//设置请求方法post或者get
public void setMethod(string method)

this.method = method;

//获取错误信息
public string getErrInfo()

return this.errInfo;

//设置证书信息
public void setCertInfo(string certFile, string certPasswd)

this.certFile = certFile;
this.certPasswd = certPasswd;

//设置ca
public void setCaInfo(string caFile)

this.caFile = caFile;

//设置超时时间,以秒为单位
public void setTimeOut(int timeOut)

this.timeOut = timeOut;


//获取http状态码
public int getResponseCode()

return this.responseCode;

public void setCharset(string charset)

if (string.IsNullOrEmpty(charset))

this.charset = "UTF-8";

this.charset = charset;

//验证服务器证书
public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)

return true;

//执行http调用
public bool call()

StreamReader sr = null;
HttpWebResponse wr = null;
HttpWebRequest hp = null;
try

string postData = null;
if (this.method.ToUpper() == "POST")

string[] sArray = System.Text.RegularExpressions.Regex.Split(this.reqContent, "\\?");
hp = (HttpWebRequest)WebRequest.Create(sArray[0]);
if (sArray.Length >= 2)

postData = sArray[1];


else

hp = (HttpWebRequest)WebRequest.Create(this.reqContent);


ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
if (this.certFile != "")

hp.ClientCertificates.Add(new X509Certificate2(this.certFile, this.certPasswd));

hp.Timeout = this.timeOut * 1000;
System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(this.charset);
if (postData != null)

byte[] data = encoding.GetBytes(postData);
hp.Method = "POST";
hp.ContentType = "application/x-www-form-urlencoded";
hp.ContentLength = data.Length;
Stream ws = hp.GetRequestStream();
// 发送数据
ws.Write(data, 0, data.Length);
ws.Close();


wr = (HttpWebResponse)hp.GetResponse();
sr = new StreamReader(wr.GetResponseStream(), encoding);

this.resContent = sr.ReadToEnd();
sr.Close();
wr.Close();

catch (Exception exp)

this.errInfo += exp.Message;
if (wr != null)

this.responseCode = Convert.ToInt32(wr.StatusCode);

return false;

this.responseCode = Convert.ToInt32(wr.StatusCode);
return true;



追问

为什么我发送之后的url 提示找不到服务器 难道服务端我只能发布之后才能测试?
这么说这个URL必须先存在 换句话说,我客户端的测试必须先写好发布是不是呢?

追答

是的,服务器的url必需存在

追问

谢谢

本回答被提问者采纳

C#怎么用Socket模拟 HTTP请求

参考技术A 已经存在webHttpRequest/WebRequest类实现web的请求,也存在WebClient等浏览器的模拟,还有轻量级的HttpClient,为什么要使用Socket模拟http请求?
如果只是出于学习的目的,那么使用reflector反射以上几个类可以直接学习的,如果是追求性能,其实httpClient的性能足够,如果是定制请求的verb,除WebClient均支持,想不起来为什么你非要使用socket模拟请求需求。
其实以上几个都是基本socket的,但是webhttpRequest是基于HttpRequest的基础类,该类的目的是实现可插入协议的开发,本身实现有FTP等几个协议;如果对于扩展协议的开发可以考虑该层。
如果你只是想学习或验证http1.1/2.0的协议,那么你直接使用filder进行构造即可验证,可然使用telnet客户端进行构造也行,只不过会麻烦一些而已。
但不管你是何目的,如果使用socket进行http请求,直接了解http协议即可。

以上是关于C#用httpclient模拟post到web网站上的主要内容,如果未能解决你的问题,请参考以下文章

如何使用HttpClient模拟浏览器GET POST

在 C# 中使用 Post 方法 HttpClient 时请求超时

C#用HttpClient类post get,怎么设置cookies

用HttpClient的post模拟搜索结果只有正常结果的一部分

带有问题网站的 HTTPclient POST

C# 模拟登录网站的cookie问题