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的更多相关文章

  1. App开发:模拟服务器数据接口 - MockApi

    为了方便app开发过程中,不受服务器接口的限制,便于客户端功能的快速测试,可以在客户端实现一个模拟服务器数据接口的MockApi模块.本篇文章就尝试为使用gradle的android项目设计实现Moc ...

  2. 干货来袭-整套完整安全的API接口解决方案

    在各种手机APP泛滥的现在,背后都有同样泛滥的API接口在支撑,其中鱼龙混杂,直接裸奔的WEB API大量存在,安全性令人堪优 在以前WEB API概念没有很普及的时候,都采用自已定义的接口和结构,对 ...

  3. 12306官方火车票Api接口

    2017,现在已进入春运期间,真的是一票难求,深有体会.各种购票抢票软件应运而生,也有购买加速包提高抢票几率,可以理解为变相的黄牛.对于技术人员,虽然写一个抢票软件还是比较难的,但是还是简单看看123 ...

  4. Java基础Map接口+Collections工具类

    1.Map中我们主要讲两个接口 HashMap  与   LinkedHashMap (1)其中LinkedHashMap是有序的  怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...

  5. Java基础Map接口+Collections

    1.Map中我们主要讲两个接口 HashMap  与   LinkedHashMap (1)其中LinkedHashMap是有序的  怎么存怎么取出来 我们讲一下Map的增删改查功能: /* * Ma ...

  6. java基础_集合List与Set接口

    List接口继承了Collection的方法  当然也有自己特有的方法向指定位置添加元素   add(索引,添加的元素); 移除指定索引的元素   remove(索引) 修改指定索引的元素   set ...

  7. 【WCF】自定义错误处理(IErrorHandler接口的用法)

    当被调用的服务操作发生异常时,可以直接把异常的原始内容传回给客户端.在WCF中,服务器传回客户端的异常,通常会使用 FaultException,该异常由这么几个东东组成: 1.Action:在服务调 ...

  8. PHP以接口方式实现多重继承(完全模拟)--学习笔记

     1.UML类图: 2.PHP代码: <?php /** * Created by PhpStorm. * User: andy * Date: 16-11-23 * Time: 下午7:57 ...

  9. 【微框架】Maven +SpringBoot 集成 阿里大鱼 短信接口详解与Demo

    Maven+springboot+阿里大于短信验证服务 纠结点:Maven库没有sdk,需要解决 Maven打包找不到相关类,需要解决 ps:最近好久没有写点东西了,项目太紧,今天来一篇 一.本文简介 ...

  10. 【接口开发】浅谈 SOAP Webserver 与 Restful Webserver 区别

    接口,强大,简单,交互,跨越平台 下面简单阐述这两大接口思想 一 REST: REST是一种架构风格,其核心是面向资源,REST专门针对网络应用设计和开发方式,以降低开发的复杂性,提高系统的可伸缩性. ...

随机推荐

  1. spring定时器

    本人小菜鸟一枚,今天在公司看到一段spring定时器配置,自己总结一下! <!-- 定义调用对象和调用对象的方法 --><bean id="jobtask9" c ...

  2. 运行impala tpch

    1.安装git和下载tpc-h-impala脚步 [root@ip-172-31-34-31 ~]# yum install git [root@ip-172-31-34-31 ~]# git clo ...

  3. C# unity3d 贪吃蛇 游戏 源码 及其感想

    这个游戏的设计过程是这样的: 1,创建

  4. AspNetPager控件分页使用方法

    AspNetPager控件官方下载地址:http://www.webdiyer.com/aspnetpager/ 把控件加到项目中(添加自定义控件的方法),并把它拖放到页面上 <asp:Scri ...

  5. SQL server存储过程语法及实例(转)

    存储过程如同一门程序设计语言,同样包含了数据类型.流程控制.输入和输出和它自己的函数库. --------------------基本语法-------------------- 一.创建存储过程cr ...

  6. C++中的文件读取结束

    while(cin>>N>>M) { } ok???

  7. spring注解 @Transactional

    一.@Transactional所需要的jar包 1.aopalliance.jar  这个包是AOP联盟的API包,里面包含了针对面向切面的接口.(通常Spring等其它具备动态织入功能的框架依赖此 ...

  8. C++ Windows进程管理

    功能: 1.各个进程启动.挂起.恢复.停止等 2.监听进程的运行状态,进程退出(正常.非正常)时,通知用户 3.异步队列 4.线程安全 进程管理器类: #ifndef __ProcessManager ...

  9. position窗口居中

    position的四个属性值: relative absolute fixed static 下面分别讲述这四个属性. <div id="parent">     &l ...

  10. ios上架报错90080,90087,90209,90125 解决办法

    ERROR ITMS-90087: "Unsupported Architectures. The executable for yht.temp_caseinsensitive_renam ...