C# http post请求帮助类
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请求帮助类的更多相关文章
- WebUtils-网络请求工具类
网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- HTTP请求工具类
HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...
- Java请求参数类QueryParameter
import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; /** * 请求 ...
- 实现一个简单的http请求工具类
OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...
- 远程Get,Post请求工具类
1.远程请求工具类 import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...
- C#实现的UDP收发请求工具类实例
本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...
- ajax请求工具类
ajax的get和post请求工具类: /** * 公共方法类 * * 使用 变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...
- 【原创】标准HTTP请求工具类
以下是个人在项目开发过程中,总结的Http请求工具类,主要包括四种: 1.处理http POST请求[XML格式.无解压]: 2.处理http GET请求[XML格式.无解压]: 3.处理http P ...
随机推荐
- font-size:0; 消除空白间隙
使用font-size:0解决设置inline-block引起的空白间隙问题 一.空白间隙问题 在进行页面布局的时候为了页面代码所谓整洁刻度,往往会设置缩进或是换行,但是元素display为inlin ...
- 2,ActiveMQ-入门
ActiveMQ是Apache出品的,非常流行的消息中间件,可以说要掌握消息中间件,需要从ActiveMQ开始.首先去官网下载:ActiveMQ官网 一,ActiveMQ目录配置文件 1.1,Acti ...
- DI,依赖注入,给对象赋值 ,get,set,list,set,map,properties对象赋值
- 对SQL 优化,提升性能!
对SQL 进行优化能够有效提高SQL 语句的执行效率,降低系统资源开销,是开发者提高后端系统处理能力的首选方案. 新产品上线后,随着运营推广活动的开始,业务进入快速增长期,数据库作为后端系统唯一或者主 ...
- mysql FULL JOIN关键字 语法
mysql FULL JOIN关键字 语法 作用:只要其中某个表存在匹配,FULL JOIN 关键字就会返回行.“富瑞华”牌大理石构件 语法:SELECT column_name(s) FROM ta ...
- 向上取整&向下取整
使用floor函数. floor(x)返回的是小于或等于x的最大整数.eg. floor(1.5) = 1 floor(-2.5) = -3 使用ceil函数. ceil(x)返回的是大于x ...
- 【CF1236D】Alice and the Doll(set)
题意:给定一个n*m的网格,其中k格有障碍 周驿东从(1,1)出发面朝右,每次行动前他可以选择顺时针旋转90度或不旋转,然后向自己朝向的位置走1格 问他能否不重复不遗漏的走过所有非障碍格 n,m,k& ...
- [CSP-S模拟测试]:木板(数学)
题目传送门(内部题68) 输入格式 输入有若干行,每行一个整数$N$,以$0$结束 输出格式 每行一个整数表示方案数,方案不同当且仅当$E$.$F$.$G$的坐标不同 样例 样例输入: 1020100 ...
- iOS Beta 升级或降级
https://sspai.com/post/45442 public beta网站上安装profile, 去手机看更新 developer beta, 登录开发者网站, downloads, 下载p ...
- Oracle JET(三)Oracle JET 响应布局
Oracle JET 提供了一系列的 CSS 样式以直接使用. Oracle JET CSS样式链接:http://docs.oracle.com/middleware/jet310/jet/refe ...