c# post basic 接口
string url = "http://xxxxxxxxx";//地址,请反复检查地址的准确性
string usernamePassword = "username:password"; byte[] bytes = Encoding.Default.GetBytes(usernamePassword);
string str = Convert.ToBase64String(bytes); string ret = new RequestHelper().HttpBasicPost(url, unionid, str);
public class RequestHelper
{ /// <summary>
/// 设置cookie
/// </summary>
private CookieContainer cookie; public CookieContainer Cookie
{
get { return cookie; }
set { cookie = value; }
} /// <summary>
/// 是否允许重定向
/// </summary>
private bool allowAutoRedirect = true;
/// <summary>
/// 是否允许重定向(默认:true)
/// </summary>
public bool AllowAutoRedirect
{
get { return allowAutoRedirect; }
set { allowAutoRedirect = value; }
} /// <summary>
/// contentType
/// </summary>
private string contentType = "application/x-www-form-urlencoded";
/// <summary>
/// 设置contentType(默认:application/x-www-form-urlencoded)
/// </summary>
public string ContentType
{
get { return contentType; }
set { contentType = value; }
} /// <summary>
/// accept
/// </summary>
private string accept = "*/*";
/// <summary>
/// 设置accept(默认:*/*)
/// </summary>
public string Accept
{
get { return accept; }
set { accept = value; }
} /// <summary>
/// 过期时间(默认:30000)
/// </summary>
private int timeOut = ; public int TimeOut
{
get { return timeOut; }
set { timeOut = value; }
} private string userAgent;
/// <summary>
///
/// </summary>
public string UserAgent
{
get { return userAgent; }
set { userAgent = value; }
}
private string acceptLanguage;
/// <summary>
/// 接受的语言
/// </summary>
public string AcceptLanguage
{
get { return acceptLanguage; }
set { acceptLanguage = value; }
}
/// <summary>
/// 处理POST请求
/// </summary>
/// <param name="url"></param>
/// <param name="postdata"></param>
/// <returns></returns>
public string HttpPost(string url, string postdata)
{
var request = CreateWebRequest(url);
request.Method = "POST";
if (!string.IsNullOrWhiteSpace(postdata))
{
var bytesToPost = Encoding.UTF8.GetBytes(postdata);
request.ContentLength = bytesToPost.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytesToPost, , bytesToPost.Length);
requestStream.Close();
}
}
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var sr = new StreamReader(response.GetResponseStream()))
{
var result = sr.ReadToEnd();
return result;
}
}
} public string HttpBasicPost(string url, string postdata, string basic)
{
var request = CreateWebRequest(url);
request.Method = "POST";
request.Headers.Add("Authorization", "Basic " + basic);
if (!string.IsNullOrWhiteSpace(postdata))
{
var bytesToPost = Encoding.UTF8.GetBytes(postdata);
request.ContentLength = bytesToPost.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytesToPost, , bytesToPost.Length);
requestStream.Close();
}
}
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var sr = new StreamReader(response.GetResponseStream()))
{
var result = sr.ReadToEnd();
return result;
}
}
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="obj"></param>
/// <returns></returns>
public T HttpPost<T>(string url, object obj)
{
var resultStr = HttpPost(url, JsonConvert.SerializeObject(obj));
return JsonConvert.DeserializeObject<T>(resultStr);
}
public T HttpPost<T>(string url, object obj, out string result, Func<string, string> serializeStrFunc = null)
{
var str = JsonConvert.SerializeObject(obj);
if (serializeStrFunc != null)
{
str = serializeStrFunc(str);
}
result = HttpPost(url, str);
return JsonConvert.DeserializeObject<T>(result);
}
/// <summary>
/// post请求返回html
/// </summary>
/// <param name="url"></param>
/// <param name="postDataStr"></param>
/// <returns></returns>
public string HttpPost(string url, Dictionary<string, string> postdata)
{
string postDataStr = null;
if (postdata != null && postdata.Count > )
{
postDataStr = string.Join("&", postdata.Select(it => it.Key + "=" + it.Value));
}
return HttpPost(url, postDataStr);
}
/// <summary>
/// get请求获取返回的html
/// </summary>
/// <param name="url">无参URL</param>
/// <param name="querydata">参数</param>
/// <returns></returns>
public string HttpGet(string url, Dictionary<string, string> querydata)
{
if (querydata != null && querydata.Count > )
{
url += "?" + string.Join("&", querydata.Select(it => it.Key + "=" + it.Value));
}
return HttpGet(url);
}
/// <summary>
/// get请求获取返回的html
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string HttpGet(string url)
{
HttpWebRequest request = CreateWebRequest(url);
request.Method = "GET";
// response.Cookies = cookie.GetCookies(response.ResponseUri);
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
var result = sr.ReadToEnd();
return result;
}
}
} protected HttpWebRequest CreateWebRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//request.ContentType = "text/html;charset=UTF-8";
request.ContentType = this.ContentType;
if (cookie != null)
request.CookieContainer = this.Cookie;
if (string.IsNullOrEmpty(this.AcceptLanguage))
{
WebHeaderCollection myWebHeaderCollection = request.Headers;
myWebHeaderCollection.Add("Accept-Language", this.AcceptLanguage);
}
request.Accept = this.Accept;
request.UseDefaultCredentials = true;
request.UserAgent = this.UserAgent;
request.Timeout = this.TimeOut;
request.AllowAutoRedirect = this.AllowAutoRedirect;
this.SetCertificatePolicy();
return request;
} /// <summary>
/// POST文件
/// </summary>
/// <param name="url"></param>
/// <param name="file">文件路径</param>
/// <param name="postdata"></param>
/// <returns></returns>
public string HttpUploadFile(string url, string file, Dictionary<string, string> postdata)
{
return HttpUploadFile(url, file, postdata, Encoding.UTF8);
}
/// <summary>
/// POST文件
/// </summary>
/// <param name="url"></param>
/// <param name="file">文件路径</param>
/// <param name="postdata">参数</param>
/// <param name="encoding"></param>
/// <returns></returns>
public string HttpUploadFile(string url, string file, Dictionary<string, string> postdata, Encoding encoding)
{
return HttpUploadFile(url, new string[] { file }, postdata, encoding);
}
/// <summary>
/// POST文件
/// </summary>
/// <param name="url"></param>
/// <param name="files">文件路径</param>
/// <param name="postdata">参数</param>
/// <returns></returns>
public string HttpUploadFile(string url, string[] files, Dictionary<string, string> postdata)
{
return HttpUploadFile(url, files, postdata, Encoding.UTF8);
}
/// <summary>
/// POST文件
/// </summary>
/// <param name="url"></param>
/// <param name="files">文件路径</param>
/// <param name="postdata">参数</param>
/// <param name="encoding"></param>
/// <returns></returns>
public string HttpUploadFile(string url, string[] files, Dictionary<string, string> postdata, Encoding encoding)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); HttpWebRequest request = CreateWebRequest(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true; ;
request.AllowAutoRedirect = this.AllowAutoRedirect;
if (this.Cookie != null)
request.CookieContainer = this.Cookie;
request.Credentials = CredentialCache.DefaultCredentials; using (Stream stream = request.GetRequestStream())
{
//1.1 key/value
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
if (postdata != null)
{
foreach (string key in postdata.Keys)
{
stream.Write(boundarybytes, , boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, postdata[key]);
byte[] formitembytes = encoding.GetBytes(formitem);
stream.Write(formitembytes, , formitembytes.Length);
}
} //1.2 file
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
byte[] buffer = new byte[];
int bytesRead = ;
for (int i = ; i < files.Length; i++)
{
stream.Write(boundarybytes, , boundarybytes.Length);
string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i]));
byte[] headerbytes = encoding.GetBytes(header);
stream.Write(headerbytes, , headerbytes.Length);
using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
{
while ((bytesRead = fileStream.Read(buffer, , buffer.Length)) != )
{
stream.Write(buffer, , bytesRead);
}
}
} //1.3 form end
stream.Write(endbytes, , endbytes.Length);
}
//2.WebResponse
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
return stream.ReadToEnd();
}
} /// <summary>
/// 获得响应中的图像
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public Stream GetResponseImage(string url)
{
Stream stream = null;
try
{
HttpWebRequest request = CreateWebRequest(url);
request.KeepAlive = true;
request.Method = "GET";
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
stream = res.GetResponseStream();
return stream;
}
catch
{
return null;
}
}
/// <summary>
/// 正则获取匹配的第一个值
/// </summary>
/// <param name="html"></param>
/// <param name="pattern"></param>
/// <returns></returns>
private string GetStringByRegex(string html, string pattern)
{
Regex re = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matchs = re.Matches(html);
if (matchs.Count > )
{
return matchs[].Groups[].Value;
}
else
return "";
}
/// <summary>
/// 正则验证返回的response是否正确
/// </summary>
/// <param name="html">Html内容</param>
/// <param name="pattern">正则表达式</param>
/// <returns></returns>
private bool VerifyResponseHtml(string html, string pattern)
{
Regex re = new Regex(pattern);
return re.IsMatch(html);
}
//注册证书验证回调事件,在请求之前注册
private void SetCertificatePolicy()
{
ServicePointManager.ServerCertificateValidationCallback
+= RemoteCertificateValidate;
}
/// <summary>
/// 远程证书验证,固定返回true
/// </summary>
private static bool RemoteCertificateValidate(object sender, X509Certificate cert,
X509Chain chain, SslPolicyErrors error)
{
return true;
} #region 提交方式
/// <summary>
/// 提交Https
/// Post
/// </summary>
/// <param name="url">URL地址</param>
/// <param name="parsStr">参数</param>
public static string SubmitHttpsPost(string url, string parsStr)
{
Encoding encode = System.Text.Encoding.UTF8;
byte[] arrB = encode.GetBytes(parsStr);
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.Method = "POST";
myReq.ContentType = "application/x-www-form-urlencoded";
myReq.ContentLength = arrB.Length;
Stream outStream = myReq.GetRequestStream();
outStream.Write(arrB, , arrB.Length);
outStream.Close(); //接收HTTP做出的响应
WebResponse myResp = myReq.GetResponse();
Stream ReceiveStream = myResp.GetResponseStream();
StreamReader readStream = new StreamReader(ReceiveStream, encode);
Char[] read = new Char[];
int count = readStream.Read(read, , );
string str = null;
while (count > )
{
str += new String(read, , count);
count = readStream.Read(read, , );
}
readStream.Close();
myResp.Close(); if (!string.IsNullOrEmpty(str))
{
return str;
}
else
{
return "无返回值";
}
} #endregion
}
basic请求的两点:
1、将用户名和密码进行编码
2、设置请求头request.Headers.Add("Authorization", "Basic " + basic);
post请求注意点:
要设置request.ContentLength,以及将表单内容写入请求中,不然会出现411长度错误
如果都尝试了还是404,请再次检查地址的准确性,在上面坑了一天!!!!!!!!!
c# post basic 接口的更多相关文章
- 几种基于HTTP协议的RPC性能比较
有了整体的了解后,可以发现Hessian的这个远程过程调用,完全使用动态代理来实现的,其实从客户端代码不难看出,HessianProxyFactory的create方法就是创建接口Basic的代理类, ...
- DBus学习笔记
摘要:DBus作为一个轻量级的IPC被越来越多的平台接受,在MeeGo中DBus也是主要的进程间通信方式,这个笔记将从基本概念开始记录笔者学习DBus的过程 [1] DBus学习笔记一:DBus学习的 ...
- 轻量级远程调用框架-Hessian学习笔记-Demo实现
Hessian是一个轻量级的remoting onhttp工具,使用简单的方法提供了RMI的功能. 相比WebService,Hessian更简单.快捷.采用的是二进制RPC协议,因为采用的是二进制协 ...
- Modbus Poll master-slave测试 Dtech USB转485(worldsing 笔记)
1,简介 网站地址:http://www.modbustools.com/ 该网站提供了几个软件工具,可以运行于windows 2000/XP/Vista/7环境下,用来测试和仿真Modebus设备. ...
- 3000本IT书籍下载地址
http://www.shouce.ren/post/d/id/112300 黑客攻防实战入门与提高.pdfhttp://www.shouce.ren/post/d/id/112299 黑 ...
- 使用CUNIT测试
使用CUNIT测试 一:概述 CUnit是一个c语言的单元测试框架,它是以静态链接库的形式,连接到用户代码中的,主要的功能就是提供了语义丰富的断言和多种测试结果输出接口,可以方便地生成测试报告. 但是 ...
- spring mvc 结合 Hessian 配置
spring mvc 结合 Hessian 配置 1.先在web.xml中配置 <!-- Hessian配置 --> <servlet> <servlet-name> ...
- modbus调试工具
1,简介 网站地址:http://www.modbustools.com/ 该网站提供了几个软件工具,可以运行于windows 2000/XP/Vista/7环境下,用来测试和仿真Modebus设备. ...
- Hessian——轻量级远程调用方案
Hessian是caucho公司开发的一种基于二进制RPC协议(Remote Procedure Call protocol)的轻量级远程调用框架.具有多种语言的实现,但用的最多的当然是Java实现 ...
随机推荐
- 兼容主流浏览器的js原生函数封装
1.获取和修改垂直滚动条的滚动距离 //获取滚动条滚动距离function getScrollTop(){ var fromTop=document.documentElement.scrollTop ...
- IOS各种手势操作实例
先看下效果 手势相关的介绍 IOS中手势操作一般是 UIGestureRecognizer 类的几个手势子类去实现,一般我们用到的手势就这么5种: 1.点击 UITapGestureRecogniz ...
- Django发送带图片和附件的邮件
最近需要做集团的SRC系统.暂无安全研发,所以只能找我这个小菜兼职开发.系统使用Django框架,在整个过程中,有许多奇特的需求.在某项需求中,需要给厂商用户发送富文本邮件,漏洞详情,这个折腾了一下, ...
- 【C语言】浅谈可变参数与printf函数
一.何谓可变参数 int printf( const char* format, ...); 这是使用过C语言的人所再熟悉不过的printf函数原型,它的参数中就有固定参数format和可变参数(用& ...
- 查看linux版本相关命令
Linux系统中,平常要装软件需要知道该系统相关信息,特别是刚刚进入公司,要接手某个系统,需要配置相关服务的时候,必须要先知道该系统的一些信息包括:内核版本信息.发行版本信息. #lsb_releas ...
- https证书申请流程和简介
HTTPS证书是什么 HTTPS(全称:Hyper Text Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单讲是HTTP的安 ...
- 初学 Java Script (数据类型)
简介:JavaScript是一种属于网络的脚本语言,已经被广泛用于Web应用开发,常用来为网页添加各式各样的动态功能,为用户提供更流畅美观的浏览效果.Javascript脚本语言同其他语言一样,有它自 ...
- Centos7:利用crontab定时执行任务
cron服务是Linux的内置服务,但它不会开机自动启动.可以用以下命令启动和停止服务: /sbin/service crond start /sbin/service crond stop /sbi ...
- vim工具
今天和同事讨论使用什么看代码,使用什么写代码的问题.我觉得source insight用来看代码真的还是蛮舒服的,但是他觉得他习惯了VS,用着顺手. 但是我的想法是,有好的工具,得先花点时间去学习使用 ...
- java复习(6)---异常处理
JAVA异常处理知识点及可运行实例 接着复习java知识点,异常处理是工程中非常重要的. 1.处理异常语句: try{ .... }catch(Exception e){ ..... } finall ...