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;
}
}
}
}

最新文章

  1. 【C#进阶系列】18 特性Attribute
  2. CP强制覆盖
  3. zt:如何快速赚取人生第一个100万?
  4. 第一个Shader的更新,增加爆光度, 属性改为数值型(更直观,精确)
  5. hdu 1195 Open the Lock
  6. PostgreSQL的 initdb 源代码分析之十五
  7. EJB (not bound)
  8. Server.MapPath(string sFilePath) 报未将对象引用到实例异常
  9. ElasticSearch基本用法
  10. SLIC superpixel实现分析
  11. PPT资料下载 - 问题驱动的软件测试设计:强化测试用例设计
  12. SpringMVC框架(三)from标签(转)
  13. 248&amp;258--高级软件工程第三次作业
  14. es6学习笔记-class之一概念
  15. 一文掌握 Linux 性能分析之 CPU 篇
  16. Ubuntu 18.04 LTS 常用软件安装杂记
  17. 安装pandas时出现环境错误
  18. Confluence 6 已经存在的 Confluence 安装配置一个数据源连接
  19. python - class propert应用
  20. Future、 CompletableFuture、ThreadPoolTaskExecutor简单实践

热门文章

  1. css盒子模型中的border属性
  2. web大文件下载+断点续传
  3. 批量下载文件JSP
  4. luogu P1028 数的计算 x
  5. 3D Computer Grapihcs Using OpenGL - 06 Vertex and Fragment Shaders
  6. Csharp随机生成序列码的方式Guid方法
  7. inux 下zip包的压缩与解压
  8. Java继承和多态-Static关键字
  9. postgresql批量删除表
  10. weui 框架