.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 ...
随机推荐
- [Angular] Bind async requests in your Angular template with the async pipe and the "as" keyword
Angular allows us to conveniently use the async pipe to automatically register to RxJS observables a ...
- [AngularFire 2] Protect Write Access Using Security Rules
We cannot allow un-auth user to change the database data as they want, for Firebase, it is easy just ...
- 微信开发学习日记(五):weiphp开源框架的bug,公众号权限编辑问题
最近在研究weiphp,总体感觉还行,bug据说还挺多. 这不,我就遇到一个比较严重影响使用的.感觉不太应该出现这么严重的bug啊. weiphp的微信公众号等级,权限增加和编辑bug,看不到权限列表 ...
- 【47.95%】【codeforces 554C】Kyoya and Colored Balls
time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...
- js 进阶 10 js选择器大全
js 进阶 10 js选择器大全 一.总结 一句话总结:和css选择器很像 二.JQuery选择器 原生javaScript中,只能使用getELementById().getElementByNam ...
- SpringMVC中支持多视图解析
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/suo082407128/article/details/70173301 在SpringMVC模式当 ...
- js进阶 9-7 自动计算商品价值
js进阶 9-7 自动计算商品价值 一.总结 一句话总结: 1.form表单控件value属性:属性可取值可赋值 2.文本onchange事件 3.form及form中控件通过name访问元素 二. ...
- bootsrap+jquery+组件项目引入文件的常见报错
做一个项目的时候 ,控制台总是会出现各种bug,其实不用慌张,终结起来也就几种类型的错误,在开发中每次遇到错误都善于总结,下次在看到就会胸有成竹知道是什么情况了,以下是在开发过程中总结的一些错误以及错 ...
- com.sun.mirror的jar包
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/sinat_36246371/article/details/53170166 <Java編程思 ...
- Windows下快速搭建安卓开发环境android-studio
Windows下快速搭建安卓开发环境android-studio 发布时间:2018-01-18 来源:网络 上传者:用户 关键字: 安卓 搭建 Android Windows 快速 环境 Studi ...