C# http post请求帮助类
2024-08-24 19:32:26
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text; namespace CommonSD
{
public class HttpPostHelper
{
public static string Post(string url, string postData)
{
return Post(url, postData, "application/x-www-form-urlencoded");
} public static string Post(string url, string postData, string contentType)
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.ContentType = contentType;
request.Method = "POST";
request.Timeout = ; byte[] bytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = bytes.Length;
Stream writer = request.GetRequestStream();
writer.Write(bytes, , bytes.Length);
writer.Close(); HttpWebResponse response = (HttpWebResponse) request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
string result = reader.ReadToEnd();
response.Close();
return result;
} public static string Post(string url, string postData, string userName, string password)
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.ContentType = "text/html; charset=UTF-8";
request.Method = "POST"; string usernamePassword = userName + ":" + password;
CredentialCache credentialCache =
new CredentialCache {{new Uri(url), "Basic", new NetworkCredential(userName, password)}};
request.Credentials = credentialCache;
request.Headers.Add("Authorization",
"Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword))); byte[] bytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = bytes.Length;
Stream writer = request.GetRequestStream();
writer.Write(bytes, , bytes.Length);
writer.Close(); HttpWebResponse response = (HttpWebResponse) request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.ASCII);
string result = reader.ReadToEnd();
response.Close();
return result;
} //static CookieContainer cookie = new CookieContainer(); /// <summary>
///
/// </summary>
/// <param name="url">请求的servlet地址,不带参数</param>
/// <param name="postData"></param>
/// <returns>请求的参数,key=value&key1=value1</returns>
public static string doHttpPost(string url, string postData)
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
SetHeaderValue(request.Headers, "Content-Type", "application/json");
SetHeaderValue(request.Headers, "Accept", "application/json");
SetHeaderValue(request.Headers, "Accept-Charset", "utf-8");
request.Method = "POST";
request.Timeout = ; byte[] bytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = bytes.Length;
Stream writer = request.GetRequestStream();
writer.Write(bytes, , bytes.Length);
writer.Close(); HttpWebResponse response = (HttpWebResponse) request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
string result = reader.ReadToEnd();
response.Close();
return result;
} /// <summary>
/// 偶发性超时时试看看
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string HttpPostForTimeOut(string url, string postData)
{
//System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
//watch.Start();
GC.Collect();
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
//request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
//int a = Encoding.UTF8.GetByteCount(postData);
request.Timeout = * * ; ServicePointManager.Expect100Continue = false;
ServicePointManager.DefaultConnectionLimit = ; request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10; Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8")); //如果JSON有中文则是UTF-8
myStreamWriter.Write(postData);
myStreamWriter.Close(); //请求中止,是因为长度不够,还没写完就关闭了. HttpWebResponse response = (HttpWebResponse) request.GetResponse();
//watch.Stop(); //停止监视
//TimeSpan timespan = watch.Elapsed; //获取当前实例测量得出的总时间
//System.Diagnostics.Debug.WriteLine("打开窗口代码执行时间:{0}(毫秒)", timespan.TotalMinutes); //总毫秒数 Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream ?? throw new InvalidOperationException(), Encoding.GetEncoding("utf-8"));
string registerResult = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return registerResult;
} public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
{
var property =
typeof(WebHeaderCollection).GetProperty("InnerCollection",
BindingFlags.Instance | BindingFlags.NonPublic);
if (property != null)
{
if (property.GetValue(header, null) is NameValueCollection collection) collection[name] = value;
}
}
}
}
最新文章
- 【C#进阶系列】18 特性Attribute
- CP强制覆盖
- zt:如何快速赚取人生第一个100万?
- 第一个Shader的更新,增加爆光度, 属性改为数值型(更直观,精确)
- hdu 1195 Open the Lock
- PostgreSQL的 initdb 源代码分析之十五
- EJB (not bound)
- Server.MapPath(string sFilePath) 报未将对象引用到实例异常
- ElasticSearch基本用法
- SLIC superpixel实现分析
- PPT资料下载 - 问题驱动的软件测试设计:强化测试用例设计
- SpringMVC框架(三)from标签(转)
- 248&;258--高级软件工程第三次作业
- es6学习笔记-class之一概念
- 一文掌握 Linux 性能分析之 CPU 篇
- Ubuntu 18.04 LTS 常用软件安装杂记
- 安装pandas时出现环境错误
- Confluence 6 已经存在的 Confluence 安装配置一个数据源连接
- python - class propert应用
- Future、 CompletableFuture、ThreadPoolTaskExecutor简单实践