接口 Post
public static StringBuilder HttpPost(string Url, byte[] Postdata, string i)
{
StringBuilder content = new StringBuilder();
try
{
WebClient wc = new WebClient();
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); byte[] bycontent = wc.UploadData(Url, "POST", Postdata);
string strcontent = System.Text.Encoding.UTF8.GetString(bycontent);
//strcontent=strcontent.Replace(""", "“");
content.Append(strcontent); }
catch (Exception ex)
{
throw new ServiceCustomException("HTTP请求失败!", ex);
}
return content;
}
第一种方式
使用:StringBuilder str = NetUtil.HttpPost(posturl, byte1, "1");
// StringBuilder sbd = NetUtil.Request(geturl, HttpMethod.GET);//此方式为Get实例
/// <summary>
/// 发出Http请求,并返回服务器的响应
/// </summary>
/// <param name="url">请求的网址</param>
/// <param name="dataToPost">post的数据</param>
/// <returns>服务器的响应</returns>
public static StringBuilder Request(string url, HttpMethod method, WebHeaderCollection headers = null, string accept = null,
string contentType = null, Encoding encoding = null, bool keepAlive = false,
int timeout = * , int readWriteTimeout = * , int writeCount = ,
CookieContainer cookieContainer = null, byte[] dataToPost = null)
{
StringBuilder result = new StringBuilder();
HttpWebRequest request = null;
HttpWebResponse response = null;
Stream responseStream = null;
StreamReader reader = null; try
{
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method.ToString(); if (headers != null)
request.Headers = headers; if (!string.IsNullOrEmpty(accept))
request.Accept = accept; if (!string.IsNullOrEmpty(contentType))
request.ContentType = contentType; request.KeepAlive = keepAlive; if (dataToPost != null && !dataToPost.Length.Equals())
{
request.ContentLength = dataToPost.Length;
} request.Timeout = timeout;
request.ReadWriteTimeout = readWriteTimeout; if (encoding == null)
encoding = Encoding.GetEncoding("utf-8"); if (method.Equals(HttpMethod.POST) && dataToPost != null && !dataToPost.Length.Equals())
{
using (Stream requestStream = request.GetRequestStream())
{
int index = ; while (index < dataToPost.Length)
{
if (dataToPost.Length - index <= writeCount)
{
requestStream.Write(dataToPost, index, dataToPost.Length - index);
index += dataToPost.Length - index;
break;
}
else
{
requestStream.Write(dataToPost, index, writeCount);
index += writeCount;
}
}
}
} if (cookieContainer == null)
request.CookieContainer = new CookieContainer();
else
request.CookieContainer = cookieContainer; response = (HttpWebResponse)request.GetResponse();
responseStream = response.GetResponseStream();
reader = new StreamReader(responseStream, encoding); string line = string.Empty; while ((line = reader.ReadLine()) != null)
{
result.Append(line);
} reader.Close();
}
catch (WebException ex)
{
throw ex;
}
catch (Exception ex)
{ }
finally
{
if (responseStream != null)
{
responseStream.Close();
responseStream = null;
}
if (reader != null)
{
reader.Close();
reader = null;
}
if (response != null)
{
response.Close();
response = null;
}
} return result;
}
第二种方式
使用: StringBuilder str = NetUtil.Request(posturl, HttpMethod.POST, null, null, "application/x-www-form-urlencoded", System.Text.Encoding.UTF8,
dataToPost: byte1);
/// <summary>
/// 提交数据请求 方法一
/// </summary>
/// <param name="POSTURL">请求提交的地址 如:http://xxx.xxx.xxx/interface/TestPostRequest</param>
/// <param name="PostData">提交的数据(字符串)</param>
/// <returns></returns>
public static string RequestData(string POSTURL, string PostData)
{
//发送请求的数据
WebRequest myHttpWebRequest = WebRequest.Create(POSTURL);
myHttpWebRequest.Method = "POST";
UTF8Encoding encoding = new UTF8Encoding();
byte[] byte1 = encoding.GetBytes(PostData);
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
//myHttpWebRequest.ContentType = "application/json";
myHttpWebRequest.ContentLength = byte1.Length;
Stream newStream = myHttpWebRequest.GetRequestStream();
newStream.Write(byte1, , byte1.Length);
newStream.Close(); //发送成功后接收返回的XML信息
HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();
string lcHtml = string.Empty;
Encoding enc = Encoding.GetEncoding("UTF-8");
Stream stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream, enc);
lcHtml = streamReader.ReadToEnd();
return lcHtml;
}
第三种方式
使用:NetUtil.RequestData(posturl, json);
public static string BuildQuery(IDictionary<string, string> parameters)
{
StringBuilder postData = new StringBuilder();
bool hasParam = false; IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
{
if (hasParam)
{
postData.Append("&");
} postData.Append(name);
postData.Append("=");
//postData.Append(UrlEncode(value));
postData.Append(value);
hasParam = true;
}
} return postData.ToString();
}
对数据进行格式化
使用:
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("canshu", "dddddddd);
string str1 = NetUtil.BuildQuery(dic); //dic为要post的所有参数
byte[] byte1 = System.Text.Encoding.UTF8.GetBytes(str1);
//posturl为传递的url参数
第三种方式中json为:string json = "canshu=" + "dddddddd";
接口 Post的更多相关文章
- App开发:模拟服务器数据接口 - MockApi
为了方便app开发过程中,不受服务器接口的限制,便于客户端功能的快速测试,可以在客户端实现一个模拟服务器数据接口的MockApi模块.本篇文章就尝试为使用gradle的android项目设计实现Moc ...
- 干货来袭-整套完整安全的API接口解决方案
在各种手机APP泛滥的现在,背后都有同样泛滥的API接口在支撑,其中鱼龙混杂,直接裸奔的WEB API大量存在,安全性令人堪优 在以前WEB API概念没有很普及的时候,都采用自已定义的接口和结构,对 ...
- 12306官方火车票Api接口
2017,现在已进入春运期间,真的是一票难求,深有体会.各种购票抢票软件应运而生,也有购买加速包提高抢票几率,可以理解为变相的黄牛.对于技术人员,虽然写一个抢票软件还是比较难的,但是还是简单看看123 ...
- Java基础Map接口+Collections工具类
1.Map中我们主要讲两个接口 HashMap 与 LinkedHashMap (1)其中LinkedHashMap是有序的 怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...
- Java基础Map接口+Collections
1.Map中我们主要讲两个接口 HashMap 与 LinkedHashMap (1)其中LinkedHashMap是有序的 怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...
- java基础_集合List与Set接口
List接口继承了Collection的方法 当然也有自己特有的方法向指定位置添加元素 add(索引,添加的元素); 移除指定索引的元素 remove(索引) 修改指定索引的元素 set ...
- 【WCF】自定义错误处理(IErrorHandler接口的用法)
当被调用的服务操作发生异常时,可以直接把异常的原始内容传回给客户端.在WCF中,服务器传回客户端的异常,通常会使用 FaultException,该异常由这么几个东东组成: 1.Action:在服务调 ...
- PHP以接口方式实现多重继承(完全模拟)--学习笔记
1.UML类图: 2.PHP代码: <?php /** * Created by PhpStorm. * User: andy * Date: 16-11-23 * Time: 下午7:57 ...
- 【微框架】Maven +SpringBoot 集成 阿里大鱼 短信接口详解与Demo
Maven+springboot+阿里大于短信验证服务 纠结点:Maven库没有sdk,需要解决 Maven打包找不到相关类,需要解决 ps:最近好久没有写点东西了,项目太紧,今天来一篇 一.本文简介 ...
- 【接口开发】浅谈 SOAP Webserver 与 Restful Webserver 区别
接口,强大,简单,交互,跨越平台 下面简单阐述这两大接口思想 一 REST: REST是一种架构风格,其核心是面向资源,REST专门针对网络应用设计和开发方式,以降低开发的复杂性,提高系统的可伸缩性. ...
随机推荐
- sublime_markdown
sublime text 下实现markdown实时预览 这个文档是网上比较流行的教程,你可以按照这个教程来,如果你幸运的话,也许一次性成功.那就到此为止,可以不用看了-- ---------–华丽的 ...
- AAS代码运行-第4章
[root@node1 aas]# ls ch02 ch03 spark--bin-hadoop2. spark--bin-hadoop2..tgz [root@node1 aas]# cd spar ...
- 场景7 Data Guard
场景7 Data Guard 官方文档 :Oracle Data Guard Concepts and Administration 用于数据容灾,通过主备库同步(主库将redo日志传送到备库,一个 ...
- JSHelper时间格式化
Helper.prototype.FormatDate = function (format) { var _now = new Date(); var o = { "M+": _ ...
- SQL sever 学习,2016,5,31,(重点:100行以后,字符串操作。)
--别名和表达式select OrderDate,YEAR(OrderDate)as 订单年份from orders; --选择select OrderDate,YEAR(OrderDate)as 订 ...
- AngulaJs+Web Api Cors 跨域访问失败的解决办法
//在服务的WebConfig文件中添加以下代码即可 //如节点已存在请去掉 <system.webServer> <httpProtocol> <customHeade ...
- Linux下PHP的完全卸载
如果想把PHP彻底的卸载干净,直接用yum的remove命令是不行的,而需要查看有多少rpm包,然后按照依赖顺序逐一卸载,在网上查了好多,都是通过 "rpm -qa | grep php& ...
- # mysql -u root -p -bash: mysql: command not found
[root@jboss ~]# mysql -u root -p-bash: mysql: command not found 需要安装mysql # yum install mysql之后就行 了
- android中所有颜色大全
< ?xml version="1.0" encoding="utf-8" ?> < resources>< colo ...
- apt-get install *** 出现 软件包***没有提供可供安装的候选者
今天,重新安装Ubuntu13.04后,在命令行输入 sudo apt-get install aptitude 提示: 软件包 aptitude 没有提供可供安装的候选者 sudo apt-get ...