.net 模拟发起HTTP请求(用于上传文件)
用C#在服务端发起http请求,附上代码一
/// <summary>
/// 文件帮助类
/// </summary>
public class FileHelper
{
/// <summary>
/// 上传文件
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="path">文件路径(带文件名)</param>
/// <returns></returns>
public static string HttpUploadFile(string url, string path)
{
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); int pos = path.LastIndexOf("\\");
string fileName = path.Substring(pos + ); //请求头部信息
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); StringBuilder builder = new StringBuilder($"Content-Disposition:form-data;name=\"subPath\"\r\n\r\ntmswechat");
byte[] postHeaderBytestwo = Encoding.UTF8.GetBytes(builder.ToString()); FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[fs.Length];
fs.Read(bArr, , bArr.Length);
fs.Close(); Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, , postHeaderBytes.Length);
postStream.Write(bArr, , bArr.Length);
postStream.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);
postStream.Write(postHeaderBytestwo, , postHeaderBytestwo.Length);
postStream.Write(endBoundaryBytes, , endBoundaryBytes.Length);
postStream.Close(); //发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
return content;
} /// <summary>
/// 上传文件
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="fs">文件流</param>
/// <param name="fileName">文件名</param>
/// <returns></returns>
public static string HttpUploadFile(string url, Stream fs, string fileName)
{
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); //请求头部信息
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); StringBuilder builder = new StringBuilder($"Content-Disposition:form-data;name=\"subPath\"\r\n\r\ntmswechat");
byte[] postHeaderBytestwo = Encoding.UTF8.GetBytes(builder.ToString()); byte[] bArr = new byte[fs.Length];
int len = fs.Read(bArr, , (int)fs.Length); Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, , postHeaderBytes.Length);
postStream.Write(bArr, , len);
postStream.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);
postStream.Write(postHeaderBytestwo, , postHeaderBytestwo.Length);
postStream.Write(endBoundaryBytes, , endBoundaryBytes.Length);
postStream.Close(); //发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
return content;
}
}
代码二
public static string HttpClientUploadFile(string url, Stream fs, string fileName)
{
if (url.StartsWith("https"))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
HttpClient httpClient = new HttpClient(); MultipartFormDataContent formData = new MultipartFormDataContent(); byte[] bArr = new byte[fs.Length];
fs.Read(bArr, , (int)fs.Length);
fs.Seek(, SeekOrigin.Begin);
ByteArrayContent byteArrayContent = new ByteArrayContent(bArr);
byteArrayContent.Headers.ContentEncoding.Add("utf-8");
formData.Add(byteArrayContent, "file", fileName);
formData.Add(new StringContent("tmswechat"), "subPath");
HttpResponseMessage response = httpClient.PostAsync(url, formData).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
return null;
}
.net 模拟发起HTTP请求(用于上传文件)的更多相关文章
- H5 FormData对象的使用——进行Ajax请求并上传文件
XMLHttpRequest Level2 添加了一个新的接口——FormData .[ 主要用于发送表单数据,但也可以独立使用于传输键控数据.与普通的Ajax相比,它能异步上传二进制文件 ] 利用F ...
- 请求与上传文件,Session简介,Restful API,Nodemon
作者 | Jeskson 来源 | 达达前端小酒馆 请求与上传文件 GET请求和POST请求 const express = require('express'); const app = expre ...
- java 模拟表单方式提交上传文件
/** * 模拟form表单的形式 ,上传文件 以输出流的形式把文件写入到url中,然后用输入流来获取url的响应 * * @param url 请求地址 form表单url地址 * @param f ...
- c#代码发送post请求,上传文件(并带其他参数)
本人对post理解不深,前段时间遇到一个需要用c#代码发送post请求上传文件的业务,于是参考了几篇帖子,加上自身实践写出了如下代码.写的比较low 望各位大大指正^_^. 业务需求: 对方给了一个接 ...
- Flask -- 请求、上传文件、Cookies
请求对象 from flask import request request.method #值为form表单提交的method 'POST'. 'GET'等 #如果值为'POST'或'PUT',则可 ...
- restTemple发送请求、上传文件(@LoadBalanced微服务调用及url调用)
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Co ...
- Django学习——ajax发送其他请求、上传文件(ajax和form两种方式)、ajax上传json格式、 Django内置序列化(了解)、分页器的使用
1 ajax发送其他请求 1 写在form表单 submit和button会触发提交 <form action=""> </form> 注释 2 使用inp ...
- 一个用于上传文件的servlet
1.jsp页面操作文件: <%@ page language="java" import="java.util.*" pageEncoding=" ...
- 使用FormData,进行Ajax请求并上传文件
前段时间做了个手机端的图片上传,为了用户体验,用ajax交互,发现了FromData对象,这里有详细解释https://developer.mozilla.org/zh-CN/docs/Web/API ...
随机推荐
- generating permunation——全排列(算法汇总)
本文一共提供了4种全排列的方法,包括递归非字典序版本.递归字典序版本.标准库版本和BFS字典序版本,当然BFS非字典序实现相对于BFS字典序版本更加简洁,稍加修改即可. 说明:递归版本基于网上现有代码 ...
- 【计算机】基本概念的理解 —— 沙盒(sandbox)、交互式计算/编程/应用
web scraper:网络铲: scraper:n. 刮刀:铲土机:守财奴: 1. 交互式计算/编程/应用(interactive computing/application/programming ...
- Spring web 工具类 WebApplicationContextUtils
概述 Spring web 的工具类 WebApplicationContextUtils 位于包 org.springframework.web.context.support 是访问一个Servl ...
- ASP.NET MVC中实现多个button提交的几种方法
有时候会遇到这样的情况:在一个表单上须要多个button来完毕不同的功能,比方一个简单的审批功能. 假设是用webform那不须要讨论,但asp.net mvc中一个表单仅仅能提交到一个Action处 ...
- RFC chinese
rfc专业性强,现实中不可能有好的全的rfc的翻译 尝试上在github上搜索 https://github.com/tidyjiang8/6lowpan-rfcs-chinese 诚如作者所说: 在 ...
- ios 第一篇文章-xcode6.2键盘调不出来
ios 第一篇文章 不晓得有没有人遇到过ios代码内调用键盘(keyboard)调不出来的情况,反正我是遇到了,按官方文档的说法调用键盘事件非常easy事实上: 我用了之后,不晓得为嘛,键盘就是不显示 ...
- amazeui-js插件-ui增强-日期组件如何使用(把实例做一下)
amazeui-js插件-ui增强-日期组件如何使用(把实例做一下) 一.总结 一句话总结:需要jquery.js和amazeui.js一切才能使用 1.amazeui中的各种js效果要怎么才能使用? ...
- 【codeforces 546B】Soldier and Badges
time limit per test3 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...
- 【codeforces 750E】New Year and Old Subsequence
time limit per test3 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...
- 二维高斯滤波器(gauss filter)的实现
我们以一个二维矩阵表示二元高斯滤波器,显然此二维矩阵的具体形式仅于其形状(shape)有关: def gauss_filter(kernel_shape): 为实现二维高斯滤波器,需要首先定义二元高斯 ...