ASP.NET的POST和GET提交并接收处理返回值
POST方法:
数据提交
/// <summary>
/// POST提交数据接收字符json
/// </summary>
/// <param name="url">远程服务器路径</param>
/// <param name="postData">提交数据</param>
/// <returns>接收数据</returns>
public static string PostData(string url, byte[] postData)
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = postData.Length; Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(postData, , postData.Length);
newStream.Close(); // Get response
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
return reader.ReadToEnd();
}
注意:POST提交必须有内容提交才可以,否则会报远程服务器返回错误: (411) 所需的长度错误。存在post内容为null的可以修改访问方式为Get
/// <summary>
/// POST提交数据接收字符json
/// </summary>
/// <param name="url">远程服务器路径</param>
/// <param name="postData">提交数据</param>
/// <returns>接收数据</returns>
public static string PostData(string url, byte[] postData)
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
if (postData != null)
{
myRequest.Method = "POST";
// Send the data.
myRequest.ContentType = "application/x-www-form-urlencoded";
//myRequest.ContentType = "application/json";//josn格式数据提交
myRequest.ContentLength = postData.Length;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(postData, , postData.Length);
newStream.Close();
}
else
{
myRequest.Method = "GET";//postData无数据时
}
// Get response
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
return reader.ReadToEnd();
}
调用POST提交结果
public string SendSMS(string mobilenumber,string content)
{
string Message = "";
//远程提交地址
string RemoteUrl = "http://www.cangcool.com/sms.action?";
string URL = RemoteUrl;
string Data = string.Format("u={0}&p={1}&m={2}&c={3}&s={4}&g={5}", _UserName, _Pwd, mobilenumber, content,"","");
byte[] ByteData=System.Text.Encoding.Default.GetBytes(Data);
Message = PostData(URL, ByteData);
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//jsonOut = serializer.Deserialize<RecordInfo>(strJsonInput);
return Message;
}
直接加载POST无参提交数据
public ActionResult PayOnline()
{
System.IO.Stream sm = Request.InputStream;
int len = (int)sm.Length;//post数据长度
byte[] inputByts = new byte[len];//字节数据,用于存储post数据
sm.Read(inputByts, , len);//将post数据写入byte数组中
sm.Close();//关闭IO流
string data = Encoding.GetEncoding("UTF-8").GetString(inputByts);//转为UTF-8编码
data = Server.UrlDecode(data);
return View(data);
}
C#POST提交文件上传
WebClient webclient = new WebClient();
byte[] responseArray = webclient.UploadFile("http://localhost:51881/API/Aliyun/UploadBusinessCard?ClientKey=111&UserID=654&File_key=file ", "POST", @"D:\1.jpg");
string getPath = System.Text.Encoding.GetEncoding("UTF-8").GetString(responseArray);
POST提交参数数据和上传文件
private static string HttpPostData(string url, int timeOut, string fileKeyName,string fileName, byte[] fileData,Dictionary<string,string> stringDict)
{
string responseContent;
var memStream = new MemoryStream();
var webRequest = (HttpWebRequest)WebRequest.Create(url);
// 边界符
var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
// 边界符
var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
//var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);//文件路径方式获取文件流
var fileStream = new MemoryStream(fileData);
// 最后的结束符
var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
// 设置属性
webRequest.Method = "POST";
webRequest.Timeout = timeOut;
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
// 写入文件
const string filePartHeader =
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
"Content-Type: application/octet-stream\r\n\r\n";
var header = string.Format(filePartHeader, fileKeyName, fileName);
var headerbytes = Encoding.UTF8.GetBytes(header);
memStream.Write(beginBoundary, , beginBoundary.Length);
memStream.Write(headerbytes, , headerbytes.Length);
var buffer = new byte[];
int bytesRead; // =0
while ((bytesRead = fileStream.Read(buffer, , buffer.Length)) != )
{
memStream.Write(buffer, , bytesRead);
}
// 写入字符串的Key
var stringKeyHeader = "\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"" +
"\r\n\r\n{1}\r\n";
foreach (byte[] formitembytes in from string key in stringDict.Keys
select string.Format(stringKeyHeader, key, stringDict[key])
into formitem
select Encoding.UTF8.GetBytes(formitem))
{
memStream.Write(formitembytes, , formitembytes.Length);
}
// 写入最后的结束边界符
memStream.Write(endBoundary, , endBoundary.Length);
webRequest.ContentLength = memStream.Length;
var requestStream = webRequest.GetRequestStream();
memStream.Position = ;
var tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, , tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, , tempBuffer.Length);
requestStream.Close();
var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
Encoding.GetEncoding("utf-8")))
{
responseContent = httpStreamReader.ReadToEnd();
}
fileStream.Close();
httpWebResponse.Close();
webRequest.Abort();
return responseContent;
}
调用方法:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
var url = "https://fileapi.instrument.com.cn/upflash/upimg.ashx"; string[] filetype = { ".rar", ".doc", ".docx", ".zip", ".pdf", ".txt", ".swf", ".wmv", ".ppt", ".pptx", ".caj", ".jpg", ".jpeg", ".gif", ".rar", ".zip", ".xls", ".xlsx" }; //文件允许格式 //文件大小限制,单位MB,同时在web.config里配置环境默认为100MB
var uploadFilesSize = IM.Utils.Configuration.AppSettings("UploadFilesSize");
var size = ;
if (!string.IsNullOrEmpty(uploadFilesSize))
{
size = Convert.ToInt32(uploadFilesSize);
}
var colname = HttpContext.Current.Request["upuser"]; if (string.IsNullOrEmpty(colname))
{
colname = "attachment";
}
var file = context.Request.Files[];
byte[] bytes = new byte[file.ContentLength];
using (BinaryReader reader = new BinaryReader(file.InputStream, Encoding.UTF8))
{
bytes = reader.ReadBytes(file.ContentLength);
}
var rel=HttpPostData(url, * * , file.FileName, file.FileName, bytes, new Dictionary<string, string>() { { "colname", colname } });
HttpContext.Current.Response.Write(rel);
}
GET方法:
数据提交
/// <summary>
/// GET提交
/// </summary>
/// <param name="strUrl">远程服务器路径</param>
/// <param name="charset">字符编码</param>
/// <returns></returns>
public static string GeData(string strUrl, string charset)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
request.Method = "GET";
request.Timeout = ;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream streamReceive = response.GetResponseStream();
Encoding encoding = Encoding.Default;
if (!string.IsNullOrEmpty(charset) && Encoding.GetEncoding(charset) != Encoding.Default)
{
encoding = Encoding.GetEncoding(charset);
} StreamReader streamReader = new StreamReader(streamReceive, encoding);
return streamReader.ReadToEnd();
}
调用GET提交结果
public string SendSMS(string mobilenumber, string content)
{
string Message = "";
//远程提交地址
string RemoteUrl = "http://www.cangcool.com/sms.action?";
string Data = string.Format("u={0}&p={1}&m={2}&c={3}&s={4}&g={5}", _UserName, _Pwd, mobilenumber, content, "", "");
string URL = RemoteUrl + Data;
Message = GeData(URL,"UTF-8");
return Message;
}
ASP.NET的POST和GET提交并接收处理返回值的更多相关文章
- ASP.NET调用存储过程并接收存储过程返回值
ASP.NET调用存储过程并接收存储过程返回值 2010-08-02 11:26:17| 分类: C#|字号 订阅 2010年02月27日 星期六 23:52 假设表结构Create T ...
- springmvc下js控制表单提交(表单提交前检验,提交后获取json返回值)
这个问题我搞了四天,终于搞懂.因为对js很不熟悉.郁闷的是后台代码出错总可以设置断点调试,前端js代码出错只能通过浏览器提供一些运行数据来分析,很不习惯. 首先说下逻辑:这是一个注册功能,我希望,注册 ...
- (四)Asp.net web api中的坑-【api的返回值】
void无返回值 IHttpActionResult HttpResponseMessage 自定义类型 我这里并不想赘述这些返回类型, 可以参考博文http://blog.csdn.net/leon ...
- ASP.Net MVC 在ajax接收controller返回值为Json数据
首先,再次回忆一下ajax的标准用法:(这张图写的比较详细了)(转) 页面部分ajax代码: $.ajax({ url: "/Home/Login?account=&q ...
- PHP模拟POST提交数据并获得返回值之CURL方法(使用PHP extension,然后使用php_curl.dll,很不错)
今天公司做个东西,需要条用同事的接口,我的代码和他的代码不在同一个域下,但是都是子域. a.ifensi.com与b.ifensi.com的关系. 我需要传递一个关联数组过去,他那边给我返回一个jso ...
- asp.net 父窗体获取子窗体的返回值,可用来对父窗体局部更新
今天在项目上遇到了这个问题,其实只是window.returnValue的简单应用,不是asp.net的专属内容.作为积累,记录一个简单的实现模型. 图1 用到的文件 从图1中我们可以看到,只用到了 ...
- ajax提交 返回值为undefined
easyui form 表单提交成功,但是返回值为undefined,原因是返回值不是json格式,是字符串的格式,那么解决办法就是把其转化成json格式 示例: $(function () { / ...
- ASP.NET MVC 之各种jQuery提交模式实例
1.$.ajax提交 var _data = { "dictItemID": dictItemID, "itemType": itemType, "i ...
- asp.net 中点击button弹出模式对话框,选择值后返回到页面中(window.showModalDialog实现)
<td>现从事专业</td><td> <asp:TextBox ID="tbMajor" runat="server ...
随机推荐
- Java-->实现群聊功能(C/S模式--TCP协议)
--> Java 对TCP协议的支持: --> java.net包中定义了两个类ServerSocket 和Socket ,分别用来实现双向连接的server 端和client 端. -- ...
- C++ Primer : 第十二章 : 动态内存之shared_ptr类
在C++中,动态内存是的管理是通过一对运算符来完成的:new ,在动态内存中为对象分配空间并返回一个指向该对象的指针,delete接受一个动态对象的指针,销毁该对象,并释放该对象关联的内存. 动态内 ...
- 不容易系列之(3)—— LELE的RPG难题
有排成一行的n个方格,用红(Red).粉(Pink).绿(Green)三色涂每个格子,每格涂一色,要求任何相邻的方格不能同色,且首尾两格也不同色.求全部的满足要求的涂法. 思路:运用递归算法. a[1 ...
- 基于Spring MVC的Web应用开发(三) - Resources
基于Spring MVC的Web应用开发(3) - Resources 上一篇介绍了在基于Spring MVC的Web项目中加入日志,本文介绍Spring MVC如何处理资源文件. 注意到本项目的we ...
- php 倒计时程序
<html> <head> <meta http-equiv="Content-Type" content="text/html; ch ...
- hihoCoder #1033 : 交错和 (数位Dp)
题目大意: 给定一个数 x,设它十进制展从高位到低位上的数位依次是 a0, a1, ..., an - 1,定义交错和函数: f(x) = a0 - a1 + a2 - ... + ( - 1)n - ...
- 【P1203】买花
我先在已经弱到连高精乘单精都能写错的地步了QAQ 原题: 求一个小于等于N的数M,使得phi(M)/M最小,其中phi(M)是与M互质且比M小的数的个数.例如phi(4)=2,因为1,3和4互质. N ...
- VC线程中操作控件,引起程序卡死的问题。
[问题还原] 线程中操作控件,具体为控制一个按键的使能,使能后结束线程. 主程序中有一个死循环,等待线程结束. 然后,就没有然后了-- [解决方案] 在主程序死循环中,如果检测到界面消息,优先处理掉.
- kuangbin_ShortPath E (POJ 1860)
第一次做判环 然后RE了五次 死在了奇怪的点 memset(vis, 0, sizeof dis); memset(dis, 0, sizeof vis); 什么鬼?? 什么鬼?? 其实代码本身还是不 ...
- Qt_Window@Qt Command Prompt从命令行创建工程
#include <QApplication> #include <QLabel> int main(int argc, char *argv[]) { QApplicatio ...