POST请求 有两种方式 一种是组装key=value这种参数对的方式 一种是直接把一个字符串发送过去 作为body的方式
我们在postman中可以看到
sfdsafd
sdfsdfds
public class KeyWordController : BaseController
{
private string listClassUrl = "http://192.168.1.171:8789/keywords/list_class";
public ActionResult List()
{
//这种方式是通过参数键值对的方式发送过去
//var para = new Dictionary<string, string>();
//para.Add("lang", "1");
//return Json(Post(listClassUrl, para));
//这种方式是整个json或者字符串发送过去
var json = @"{""lang"":1}";
return Json(Post(listClassUrl, json),JsonRequestBehavior.AllowGet);
}
/// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
private string Post(string url, Dictionary<string, string> dic)
{
string result = string.Empty;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
#region 添加Post 参数
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
/// <summary>
/// POST整个字符串到URL地址中
/// </summary>
/// <param name="Url"></param>
/// <param name="jsonParas"></param>
/// <returns></returns>
public string Post(string Url, string jsonParas)
{
string strURL = Url;
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
//内容类型
//request.ContentType = "application/x-www-form-urlencoded";
//设置参数,并进行URL编码
string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);
byte[] payload;
//将Json字符串转化为字节
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
//设置请求的ContentLength
request.ContentLength = payload.Length;
//发送请求,获得请求流
Stream writer;
try
{
writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
}
catch (Exception)
{
writer = null;
Console.Write("连接服务器失败!");
}
//将请求参数写入流
writer.Write(payload, 0, payload.Length);
writer.Close();//关闭请求流
//String strValue = "";//strValue为http响应所返回的字符流
HttpWebResponse response;
try
{
//获得响应流
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
Stream s = response.GetResponseStream();
Stream postData = Request.InputStream;
StreamReader sRead = new StreamReader(s);
string postContent = sRead.ReadToEnd();
sRead.Close();
return postContent;//返回Json数据
}
POST方式提交数据,一种众所周知的方式:
html页面中使用form表单提交,接收方式,使用Request.Form[""]或Request.QueryString[""]来获取。
这里介绍另外一种POST方式和接收方式,就是将整个数据作为加入到数据流中提交和接收
接收方式:
Stream s = System.Web.HttpContext.Current.Request.InputStream; byte[] b = new byte[s.Length]; s.Read(b, 0, (int)s.Length); return Encoding.UTF8.GetString(b);
只需要从input Stream中读取byte数据,然后转为string,再解析即可。如果要回复响应消息只需要用:Response.Write() 输出即可(和普通的页面输出一样)。
今天在手机App测试接口的时候发现一个通过POST方式的接口 获取body中的参数一直为空,但是在数据量小的时候却可以获取到数据,开始怀疑是不是POST的长度有限制,然后在web.config中修改了一下maxRequestLength,如下
1
2
3
|
<system.web> <httpRuntime targetFramework= "4.5" maxRequestLength= "20480" />
</system.web>
|
然后发现 获取的值还是为空,然后在调试的过程中发现当数据量多的时候Request.InputStream的Position居然是在结束位置,如下图
从上图可以看出,因为Request.InputStream肯定是被读过了所以Position会在结束位置,一般Positon都是0。所以获取body中的参数一直为空,知道原因后在读取流之前把Position设置为0就可以了
1
2
3
4
5
6
7
8
|
var stream = HttpContext.Current.Request.InputStream;
stream.Position = 0;
using ( var streamReader = new StreamReader(stream, Encoding.UTF8))
{
requestData = streamReader.ReadToEndAsync().Result;
requestData = ( "appKey" + appKey + requestData + "timestamp" + timestamp).ToUpper();
stream.Position = 0;
}
|