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. 【leetcode】540. Single Element in a Sorted Array

    题目如下: 解题思路:题目要求时间复杂度是O(logN),可以尝试使用二分查找法.首先数组是有序的,而且仅有一个元素出现一次,其余均为两次.我们可以先找到数组最中间的元素,记为mid.如果mid和mi ...

  2. POST接口测试的请求方式

    一.基础知识 1.HTTP的八种请求方法:GET, POST ,HEAD,OPTIONS, PUT, DELETE, TRACE 和 CONNECT 方法. GET请求:请求指定的页面信息,并返回实体 ...

  3. 事物 @Transactional

    转载:http://www.cnblogs.com/kristain/articles/2038397.html 一.什么是事务 事务是访问数据库的一个操作序列,数据库应用系统通过事务集来完成对数据库 ...

  4. Java——package与import

    [package]   <1>为了解决类的命名冲突问题,Java引入包(package)机制,提供类的多重类命名空间. <2>package作为源文件的第一条语句(缺省时指定为 ...

  5. python魔法属性

    1.__doc__:表示类的描述信息 class Person(object): '''定义人的类''' def func(self): pass print(Person.__doc__) 结果为: ...

  6. JavaScript实现Tab标签页切换的最简便方式

    转载请注明出处:http://www.cnblogs.com/-867259206/p/5664896.html 先说一下最土的一种方法: Html: <div class="tab- ...

  7. Minimum Cut

    Minimum Cut Time Limit: 3000/2000 MS (Java/Others)    Memory Limit: 65535/102400 K (Java/Others)Tota ...

  8. ionic使用自定义icon

    参考文档:https://www.jianshu.com/p/5346fee9fd80  angular+ionic 自定义图标 注意: 这里不用name 用class类名显示出来 最后出来图标是个小 ...

  9. Java中使用Redis的几种数据类型总结

    1.String,最基本的类型 方法  set.get 2.hash redis 127.0.0.1:6379> HMSET user:1 username redis.net.cn passw ...

  10. Sublime如何设置背景透明

    Sublime如何设置背景透明 下载sublime 透明背景插件 我用的是git下载插件: git clone https://github.com/vhanla/SublimeTextTrans.g ...