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# http post请求帮助类的更多相关文章

  1. WebUtils-网络请求工具类

    网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...

  2. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  3. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

  4. HTTP请求工具类

    HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...

  5. Java请求参数类QueryParameter

    import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; /** * 请求 ...

  6. 实现一个简单的http请求工具类

    OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...

  7. 远程Get,Post请求工具类

    1.远程请求工具类   import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...

  8. C#实现的UDP收发请求工具类实例

    本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...

  9. ajax请求工具类

    ajax的get和post请求工具类: /** * 公共方法类 *  * 使用  变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...

  10. 【原创】标准HTTP请求工具类

    以下是个人在项目开发过程中,总结的Http请求工具类,主要包括四种: 1.处理http POST请求[XML格式.无解压]: 2.处理http GET请求[XML格式.无解压]: 3.处理http P ...

随机推荐

  1. 解决GitHub加载不出图片问题

    解决方法: 复制 raw.githubusercontent.com 去 https://www.ipaddress.com 搜索,把给出的IP地址存储到 host 文件中: 如 199.232.28 ...

  2. 【NOIP2016提高A组模拟8.14】疯狂的火神

    题目 火神为了检验zone的力量,他决定单挑n个人. 由于火神训练时间有限,最多只有t分钟,所以他可以选择一部分人来单挑,由于有丽子的帮助,他得到了每个人特定的价值,每个人的价值由一个三元组(a,b, ...

  3. requiredBackgroundModes

    申明需要后台运行的能力,类型为数组.目前支持以下项目: audio: 后台音乐播放如: { "pages": ["pages/index/index"], &q ...

  4. Wannafly挑战赛16 #E 弹球弹弹弹 splay+基环树+各种思维

    链接:https://ac.nowcoder.com/acm/problem/16033来源:牛客网 有n个位置,标号为1到n的整数,m次操作,第i次操作放置一个弹球在b[i] xor c[i-1]处 ...

  5. Java——容器(Interator)

    [Interator接口]   <1> 所有实现了Collection接口的容器类都有一个interator方法用以返回一个实现了Interaor接口的对象. <2> Inte ...

  6. formdata方式上传文件,支持大文件分割上传

    1.upload.html <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/html"> <h ...

  7. Online Game Development in C++ 第五部分总结

    I. 教程案例框架描述 该套教程做了一个简单的汽车控制系统,没有用到物理模拟.用油门和方向控制汽车的加速度和转向,同时还有一些空气阻力和滚动摩擦力的设置增加了真实感.汽车的位置是通过加速度和时间等计算 ...

  8. 学习wavenet_vocoder之预处理、训练

    一.预处理 1.在进行预处理时,如果不明白需要的参数,可以使用命令获取帮助,从这里我们可以看到可以具体的用法和对应的参数. python preprocess.py --help python pre ...

  9. C#配置IIS站点

    一.源码特点       1.  一些基于ASP.NET应用产品,在用户环境中都无可避免的涉及到部署到目标环境的应用服务器上,而配置站点是此过程的核心步骤,此源码对过程进行了高度封装,从创建IIS所需 ...

  10. React Native商城项目实战16 - 购物中心详细页

    逻辑分析: 首页(Home)加载的购物中心组件(ShopCenter),传递url数据: ShopCenter里根据url加载购物中心详细页组件(ShopCenterDetail), ShopCent ...