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. Jmeter性能测试入门(转)

    出处:http://www.cnblogs.com/by-dream/p/5611555.html Jmeter性能测试步骤 1. 添加线程组之后,先设置这两项: 2. 添加一个http请求 被测的u ...

  2. FTP Proxy Server

    本文将在Linux环境下实现一个简单的FTP代理服务器,主要内容涉及FTP主动/被动模式和简单的Socket编程. 1. 主动模式和被动模式 FTP有两种模式,即主动模式(Active Mode)和被 ...

  3. 使用NSJSONSerialization将数组或字典转为字符串

    IOS中将数组或字典转为字符串可以用NSJSONSerialization,代码如下: NSData* data = [NSJSONSerialization dataWithJSONObject:a ...

  4. Python开发入门与实战22-简单消息回复

    22. 简单消息回复 本章节我们来实现一个微信库存查询功能,使用我们前面的BIZ业务逻辑层示例如何利用微信入口来实现文本消息类的库存查询服务. 22.1. 在responseMsg函数里增加处理微信文 ...

  5. git clone错误

    git clone错误 Initialized empty Git repository in ***/.git/ error: The requested URL returned error: 4 ...

  6. 无约束优化算法——牛顿法与拟牛顿法(DFP,BFGS,LBFGS)

    简介:最近在看逻辑回归算法,在算法构建模型的过程中需要对参数进行求解,采用的方法有梯度下降法和无约束项优化算法.之前对无约束项优化算法并不是很了解,于是在学习逻辑回归之前,先对无约束项优化算法中经典的 ...

  7. css3 文字轮番滚动效果2——改进版

    1.优化了之前的代码: 2.修正了先前按照文字的条目的数量计算速度的问题,现在改为按照字符的个数计算动画执行一次需要的时间,更为精确: 3.增添了每一行JS代码的注释. 4.这个案例的用途一般为告警信 ...

  8. Python基础知识之排序法

    在Python开发中,我们会经常使用到排序法,排序的最简单的方法是用sort(list)函数,它接受一个列表并返回与有序的元素一个新的列表. 原始列表不被改变. a = [5, 1, 4, 3]    ...

  9. 利用border-radious画图形

    今天才发现,border-radius可以画很多图形,下面跟我来看一下吧: 在设有宽和高的情况下画一个圆: #div1{ /*宽高相等,圆角范围为高或宽的一半或以上*/ background-colo ...

  10. 802.11MAC基础

    做无线网络测试已经大半年了,在这过程中发现<802.11权威指南>真是以本好书,在这里分享一下学习到的知识,也帮助我记忆. 1.MAC: mac(媒介访问控制层),它位于物理层之上,控制着 ...