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. SYN攻击

    一.TCP握手协议 在TCP/IP协议中,TCP协议提供可靠的连接服务,采用三次握手建立一个连接. 第一次握手:建立连接时,客户端发送syn包(syn=j)到服务器,并进入SYN_SEND状态,等待服 ...

  2. classpath路径和properties

    在Java程序中,一般情况下使用绝对路径还是相对路径都不太合适,因为Java程序的jar包所放的位置不确定,执行java程序时当前的路径也不确定,所以不合适.一般在Java程序中我们会把资源放到cla ...

  3. keep the bar green to keep the code clean——Junit详解(二)

    测试用例&测试套件 举个栗子: 编写MyStack类模拟栈,并对其进行测试用例编写测试: 编写文件删除方法,并对其删除测试. 不再做演示,戳此获取代码 MyStack类: public cla ...

  4. rocksDB 安装问题简单介绍

    前一段时间准备测试rocksdb,按照帖子和官网的例子,在安装过程中遇到一些问题.这里给出的是在Ubuntu下安装python使用的版本. 首先,要感谢这些帖子对我的帮助: 1:http://tech ...

  5. AngularJs的UI组件ui-Bootstrap分享(十一)——Typeahead

    Typeahead指令是一个用于智能提示或自动完成的控件,就像Jquery的AutoComplete控件一样.来看一个最简单的例子: <!DOCTYPE html> <html ng ...

  6. JAVA时间格式转换大全

    import java.text.*; import java.util.Calendar; public class VeDate { /** * 获取现在时间 * * @return 返回时间类型 ...

  7. 软件测试第六周学习笔记之“Win8 APP应用程序的白盒测试”

    这周的学习笔记我想写点自己关于实验中碰到的问题和感想. 因为这次做的是白盒测试,所以我决定去测试一下上回测试的app的功能函数. 这次我用的是单元测试项目来做的白盒测试: 创建单元测试的步骤: 1.点 ...

  8. php 错误处理函数

    eval()   把子符串当做php 代码执行 // 回调函数function a($b, $c) { echo $b; echo $c; } call_user_func_array('a', ar ...

  9. Apache Tomcat开机后台启动

    作为软件开发人员,经常接触Tomcat,完成的项目,需要部署到服务器上的Tomcat,才能供其他人访问浏览. 因为存在以下问题,所以需要把Tomcat设置为后台自动启动: 1.服务器可能因环境故障面临 ...

  10. SQL中随机数函数rand()简介

    转自:http://database.51cto.com/art/201009/224397.htm 下文将为您介绍SQL中的随机函数rand(),供您参考,如果您是才接触SQL Server的新手, ...