利用HttpWebRequest模拟表单提交

  1 using System;
  2 using System.Collections.Specialized;
  3 using System.IO;
  4 using System.Net;
  5 using System.Text;
  6
  7 namespace Allyn.Common
  8 {
  9     public class HttpHelper
 10     {
 11         /// <summary>
 12         /// 获取指定路径数据
 13         /// </summary>
 14         /// <param name="requestUri">提交路径</param>
 15         /// <param name="cookie">Cookie容器对象</param>
 16         /// <returns>字符串结果</returns>
 17         public static string GetForm(string requestUri, CookieContainer cookie)
 18         {
 19             HttpWebRequest request = WebRequest.CreateHttp(requestUri);
 20             request.Method = "get";
 21             request.CookieContainer = cookie;
 22             request.ContentLength = 0;
 23
 24             WebResponse response = request.GetResponse();
 25             StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
 26             return reader.ReadToEnd();
 27         }
 28
 29         /// <summary>
 30         /// 默认表单提交
 31         /// </summary>
 32         /// <param name="requestUri">提交路径</param>
 33         /// <param name="postData">提交数据</param>
 34         /// <param name="cookie">Cookie容器对象</param>
 35         /// <returns>字符串结果</returns>
 36         public static string PostForm(string requestUri, NameValueCollection postData, CookieContainer cookie)
 37         {
 38             HttpWebRequest request = WebRequest.CreateHttp(requestUri);
 39             request.Method = "post";
 40             request.ContentType = "application/x-www-form-urlencoded";
 41             request.CookieContainer = cookie;
 42
 43             StringBuilder stringBuilder = new StringBuilder();
 44             foreach (string key in postData.Keys)
 45             {
 46                 stringBuilder.AppendFormat("&{0}={1}", key, postData.Get(key));
 47             }
 48             byte[] buffer = Encoding.UTF8.GetBytes(stringBuilder.ToString().Trim(‘&‘));
 49             Stream requestStream = request.GetRequestStream();
 50             requestStream.Write(buffer, 0, buffer.Length);
 51             requestStream.Close();
 52
 53             WebResponse response = request.GetResponse();
 54             StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
 55             return reader.ReadToEnd();
 56         }
 57
 58         /// <summary>
 59         /// 多部件表单提交
 60         /// </summary>
 61         /// <param name="requestUri">提交路径</param>
 62         /// <param name="postData">提交数据.注:如果是文件路径,代表是文件.</param>
 63         /// <param name="cookie">Cookie容器对象</param>
 64         /// <returns>字符串结果</returns>
 65         public static string PostFormMultipart(string requestUri, NameValueCollection postData, CookieContainer cookie)
 66         {
 67             string boundary = string.Format("-----{0}", DateTime.Now.Ticks.ToString("x"));
 68             HttpWebRequest webrequest = WebRequest.CreateHttp(requestUri);
 69             webrequest.CookieContainer = cookie;
 70             webrequest.Timeout = 120000;
 71             webrequest.Method = "post";
 72             webrequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
 73
 74             Stream requestStream = webrequest.GetRequestStream();
 75             foreach (string key in postData.Keys)
 76             {
 77                 StringBuilder strBuilder = new StringBuilder();
 78                 strBuilder.AppendFormat("--{0}", boundary);
 79                 strBuilder.AppendFormat("\r\nContent-Disposition: form-data; name=\"{0}\"", key);
 80                 if (File.Exists(postData.Get(key)))
 81                 {
 82                     strBuilder.AppendFormat(";filename=\"{0}\"\r\nContent-Type: multipart/form-data\r\n\r\n", Path.GetFileName(postData.Get(key)));
 83                     byte[] buffer = Encoding.UTF8.GetBytes(strBuilder.ToString());
 84                     requestStream.Write(buffer, 0, buffer.Length);
 85                     //获取图片流
 86                     FileStream fileStream = new FileStream(postData.Get(key), FileMode.Open, FileAccess.Read);
 87                     BinaryReader binaryReader = new BinaryReader(fileStream);
 88                     byte[] fileBuffer = binaryReader.ReadBytes((int)fileStream.Length);
 89                     binaryReader.Close();
 90                     fileStream.Close();
 91                     requestStream.Write(fileBuffer, 0, fileBuffer.Length);
 92                 }
 93                 else
 94                 {
 95                     strBuilder.AppendFormat("\r\n\r\n{0}\r\n", postData.Get(key));
 96                     byte[] buff = Encoding.UTF8.GetBytes(strBuilder.ToString());
 97                     requestStream.Write(buff, 0, buff.Length);
 98                 }
 99             }
100
101             byte[] boundaryBuffer = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}\r\n", boundary));
102             requestStream.Write(boundaryBuffer, 0, boundaryBuffer.Length);
103             requestStream.Close();
104
105             WebResponse response = webrequest.GetResponse();
106             StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
107             return reader.ReadToEnd();
108         }
109     }
110 }

原文地址:https://www.cnblogs.com/allyn/p/10177888.html

时间: 2024-12-01 19:54:40

利用HttpWebRequest模拟表单提交的相关文章

Java利用Http模拟表单提交

private static String sendPost(String url, NameValuePair[] params) { HttpClient client = new HttpClient(); // 请求超时 client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000); // 读取超时 client.getParams().setParameter(CoreConnection

利用js模拟表单提交

1.添加js跳转方法 function post(URL, PARAMS) { var temp = document.createElement("form"); temp.action = URL; temp.method = "post"; temp.style.display = "none"; for (var x in PARAMS) { var opt = document.createElement("textarea&

C# Winform利用POST传值方式模拟表单提交数据(Winform与网页交互)

其原理是,利用winfrom模拟表单提交数据,将要提交的参数提交给网页,网页执行代码,得到数据,然后Winform程序将网页的所有源代码读取下来,这样就达到windows应用程序和web应用程序之间传参和现实数据的效果了. - 首先创建一个windows应用程序和web应用程序. - 在web应用程序中,将网页切换到源代码并把源代码中一些没用的代码删掉,只保留头部,在windows应用程序读取网页源码时,这些都会被一起读下来,但这些都是没用的数据,而且删掉没什么影响.需要保留的代码如下: - <

HTTP通信模拟表单提交数据

前面记录过一篇关于http通信,发送数据的文章:http://www.cnblogs.com/hyyq/p/7089040.html,今天要记录的是如何通过http模拟表单提交数据. 一.通过GET请求方式提交:最简单的一种方式 直接在链接后面跟上要提交的数据即可,比如: http://yychf.55555.io/get.do?username=yyc&password=yychf,通过http直接发送.然后在服务器端可以通过request.getParameter()方法来获得参数值.如要获

表单提交---前端页面模拟表单提交(form)

有些时候我们的前端页面总没有<form></form>表单,但是具体的业务时,我们又必须用表单提交才能达到我们想要的结果,LZ最近做了一些关于导出的一些功能,需要调用浏览器默认的下载功能,如果用ajax请求,则无法调用.所以只能用表单提交的方式请求后台方可调用浏览器默认的下载功能.这个时候我们只能自己手动添加<form></form>元素.这里LZ提供我自己遇到的两种情况: 一:在原有的html结构包上<form></form>标签,

&lt;记录&gt; axios 模拟表单提交数据

ajax 可以通过 FormData 对象模拟表单提交数据 第一种方式:自定义FormData信息 //创建formData对象 var formData = new FormData(); //添加键值对 formData.append("team_id", this.team_id) formData.append("content", this.content) formData.append("img", this.img) formDa

c# 模拟表单提交,post form 上传文件、大数据内容

表单提交协议规定:要先将 HTTP 要求的 Content-Type 设为 multipart/form-data,而且要设定一个 boundary 参数,这个参数是由应用程序自行产生,它会用来识别每一份资料的边界 (boundary),用以产生多重信息部份 (message part).而 HTTP 服务器可以抓取 HTTP POST 的信息, 基本内容:1. 每个信息部份都要用 --[BOUNDARY_NAME] 来包装,以分隔出信息的每个部份,而最后要再加上一个 --[BOUNDARY_N

java后端模拟表单提交

代码可实现文本域及非文本域的处理 请求代码: /** * 上传 * * @param urlStr * @param textMap * @param fileMap * @return */ public static String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) { String res = ""; HttpURLConne

ajax模拟表单提交,后台使用npoi实现导入操作 方式一

页面代码: <form id="form1" enctype="multipart/form-data"> <div style="float:right">   <button type="button" class="btn btn-primary" onclick="$('#fileUpload').click()" id="reviewFi