接口 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专门针对网络应用设计和开发方式,以降低开发的复杂性,提高系统的可伸缩性. ...
随机推荐
- 一张关于docker版本的图
今天安装了windows内测版的docker,的确是是把vitualbox换成了hyper-v,如左图,server的os 还是linux.不过之前在nanoserver上装的docker 也的确是原 ...
- iOS程序启动过程
First, the function creates the main application object (step 3 in the flowchart). If you specify ni ...
- AsyncTask异步交互和httpurlconnection结合使用
//网络请求数据 package com.baidu.myutils; import java.io.BufferedReader; import java.io.InputStreamReader; ...
- 作业七:团队项目——Alpha版本冲刺阶段006
今日进展:完成主体代码. 今日安排:对程序主体进行编写.
- thymeleaf常用标签
1. th:checked ,th:selected标签<input type="radio" value="M" name="gender&q ...
- Dapper学习笔记(5)-存储过程
一.无参存储过程 第一步:创建一个不带参数的存储过程,代码如下: CREATE PROCEDURE [dbo].[QueryRoleNoParms] AS BEGIN SELECT * FROM T_ ...
- Android开源框架:NineOldAndroid
在android3.0以前的版本,要实现动画,一般是使用NineOldAndroid开源框架,之后,就可以直接使用android提供的animation API了. 仔细看过此开源框架后,可看出此框架 ...
- js和jquery获取图片真实的宽度和高度
1.什么时候需要获取图片真实的宽度和高度 在做pc网页的时候,有时候会考虑按照插入的图片的尺寸来判断图片是横图还是竖图.然后判断过后给予不同的展示方式! 另外一种就是在手机页面上,在新闻页插入的图片往 ...
- taginput ,complete使用笔记
页面用到自动完成功能及需要taginput控件去展示,查资料的过程中发现 有两个类似的jQuery类库,到现在我也没搞明白它们两个有啥关联,jquery.tagsinput.js和bootstrap- ...
- Spring中配置文件中引用外部文件
src\dayday\conn.java package dayday;import java.sql.Connection;import java.sql.DriverManager;import ...