.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 ...
随机推荐
- ZOJ FatMouse' Trade 贪心
得之我幸,不得,我命.仅此而已. 学姐说呀,希望下次看到你的时候依然潇洒如故.(笑~) 我就是这么潇洒~哈哈. 感觉大家比我还紧张~ 我很好的.真的 ------------------------- ...
- term- xshell VS securecrt
Xshell使用技巧总结 https://www.cnblogs.com/zhangwuji/p/7155575.html SecureCRT与Xshell简单对比 http://ju.outofme ...
- css3-7 如何让页面元素水平垂直都居中(元素定位要用css定位属性)
css3-7 如何让页面元素水平垂直都居中(元素定位要用css定位属性) 一.总结 一句话总结:元素定位要用css定位属性,而且一般脱离文档流更加好操作.先设置为绝对定位,上左都50%,然后margi ...
- solaris 11 stdio.h: No such file or directory
http://www.zendo.name/solaris-11-stdio-h%EF%BC%9A-no-such-file-or-directory/ Posted on 2012 年 3 月 23 ...
- 解析C#内存管理
C#内存管理解析 前言:对于很多的C#程序员来说,经常会很少去关注其内存的释放,他们认为C#带有强大的垃圾回收机制,所有不愿意去考虑这方面的事情,其实不尽然,很多时候我们都需要考虑C#内存的管理问题, ...
- 【42%】【hdu1166】排兵布阵(树状数组解法&&线段树解法)
Problem Description C国的死对头A国这段时间正在进行军事演习,所以C国间谍头子Derek和他手下Tidy又开始忙乎了.A国在海岸线沿直线布置了N个工兵营地,Derek和Tidy的任 ...
- [NPM] Add comments to your npm scripts
The need for comments in your package.json file becomes desirable the more and more npm scripts you ...
- Python 数组[],元组(),字典{}的异同
序列 Python有6中内建的序列,在这里我们重点讨论两种,数组和元组.所有序列都可以做某些特定的操作,大致上常用的是:加,乘,索引,分片以及检查某个元素是否属于序列的成员. Python还提供一些内 ...
- 关于使用Timer定时监测网络是否ping通
项目需要连接某台具体服务端,如果连不上则实时提示,开始使用Timer实时检测 void timer_Tick(object sender, EventArgs e) { Ping pingSender ...
- 12个被滥用的Android应用程序权限
Android应用程序须要权限才干正常运作,只是网络犯罪分子会将其用在个人私利上.来看看最常被要求的权限以及它们会怎样被滥用. .网络定位功能 这代表什么:同意应用程序通过网络定位(像是基地台或无线网 ...