(C#语言) httpClient使用put方式提交multiparty/form-data 数据类型 的 csv格式的文件【bear token鉴权】
2022/1/28 14:04:25
本文主要是介绍(C#语言) httpClient使用put方式提交multiparty/form-data 数据类型 的 csv格式的文件【bear token鉴权】,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
要求C#语言在微博service接口中使用content-type:multiparty/form-data属性,上传csv文件,且头部添加bear格式的jwt鉴权。实现通过接口完成批量数据的传输及同步。
//全局变量
public string urlHost=“”;
#region 主函数
[WebMethod(Description="连通性测试")]
public void TestBatch()
{
urlHost="http://22.22.22.22.:8089/tencent";
if(!string.IsNullOrEmpty(urlHost))
{
//根目录
string departID = "tt-6e4rrtty4579dsfs96";
//urlHost 访问地址的接口地址
urlHost+=string.Format(@"/api/v"+departID +"/obj?obj=user");
#region 创建文件
DateTime dt = DateTime.Now;
string TencentBatch=ConfigurationManager.AppSettings["mulu1"];
string headPath=ConfigurationManager.AppSettings["mulu2"];
string middlePath=TencentBatch+dt.Year+"/"+(dt.Month<10?"0":"")+dt.Month+"/"+(dt.Day<10?"0":"")+dt.Day+"/";
if(!System.IO.Directory.Exists(headPath+middlePath.Replace("/","\\")))
{
Directory.CreateDirectory(headPath+middlePath.Replace("/","\\"));
}
//eg:D:\\测试文件夹\\测试1\\测试2\2022\01\22\aa_1_1.csv
string path = headPath+middlePath.Replace("/","\\")+"aa_1_1.csv";
int pos=path.LastIndexOf("\\");
string fileName=path.Substring(pos+1);
string firstLine=string.Format(@"id,modifiedOn");
//tchModel上送模板的列明,
List<tchModel> lt = new List<tchModel>();
tchModel tmbm = new tchModel();
tmbm .id="id2";
tmbm .modifiedOn="2022/02/02";
lt.Add(tmbm);
bool bl=WriteFile<tmbm>(path,lt,firstLine);
#endregion
//自定义请求方式
HttpRequestMessage requestMessage=new HttpRequestMessage();
requestMessage.Method = HttpMethod.Put;
requestMessage.RequestUri = new Uri(urlHost);
//1.数据流存入
Stream fileStream=new FileStream(path,FileMode.Open,FileAccess.Read);
var formData=new MultipartFormDataContent();
formData.Add(new StreamContent(fileStream),"file",fileName);
/*
//2.字节存入
Stream fileStream=new FileStream(path,FileMode.Open,FileAccess.Read);
byte[] data = new byte[fileStream.Length]
fileStream.Read(data,0,data.Length);
fileStream.Close();
formData.Add(new ByteArrayContent(data),"file",fileName);
*/
requestMessage.Content=formData;
/*
//!注意:千万别指定Content-Type的multiparty/form-data属性,因为该属性会添加boundary属性,其是不可控的。
//这个值有浏览器生成的。如果强行指明很可能导致边界值不一致而失败。报错信息为
//result{ StatusCode:400,ReasonPhrase:'Bad Request',Version:1.1,Content:System.Net.Http.StreamContent,Headers:{ i-transaction-id:9bfe3a88-cla8-43df-b9b9-630fdef601de
//x-envoy-upstream-service-time:16
//Connection:close
//Date:Thu,27 Jan 2022 08:09:17 GMT
//Server:nginx
//Content-Length:0 } }
string boundary =string.Format(“-------test{0}-------”,DateTime.Now.Ticks.ToString("x"));
formData =new MultipartFormDataContent(boundary);
requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
*/
HttpClient client = new HttpClient();
var authenticationHeaderValue = new AuthenticationHeaderValue("Bearer",GetToken());
client.DefaultRequestHeaders.Authorization = authenticationHeaderValue;
client.DefaultRequestHeaders.Add("CharSet","utf-8");
HttpResponseMessage result = client.SendAsync(requestMessage).Result;
string responseResult = result.Content.ReadAsStringAsync().Result;
client.Dispose();
fileStream.Close();
try{
if(result.IsSuccessStatusCode)
{
string r=result.Content.ReadAsStringAsync().Result;
Context.Response.Write(r);
}
}finally{
fileStream.Close();
client.Dispose();
}
}
}
#endregion
//====================生成文件===================
public static bool WriteFile<T>(string fileName,List<T> dataTable,string firstLine)
{
bool flag = false;
try{
if(File.Exists(fileName))
{
File.Delete(fileName);
}
using(FileStream fs=new FileStream(fileName,FileMode.Create))
{
//指定Encodeing.UTF8,避免生成的文件乱码
using(StreamWriter sw = new StreamWriter(fs,Encodeing.UTF8))
{
string info Line= string.Empty;
sw.WriteLine(firstLine);
foreach(var item in dataTable)
{
infoLine +=",,";
}
sw.Close();
}
fs.Close();
}
}
}
//-----生成J问题Token---
public string Get Token()
{
var headers = new Dictionary<string,object>(){
{"type","JWT"},
{"kid","58888888-8888-8888-8888-888888888888"}
};
long iat =(long)DateTime.Now.ToUniversalTime().Subtract(new DateTime(1970,1,1)).TotalSeconds;
long exp =(long)DateTime.Now.AddMinutes(1.0).ToUniversalTime().Subtract(new DateTime(1970,1,1)).TotalSeconds;
var claims = new Dictionary<string,object>()
{
{"aud","test"},
{"iss","22222222-2222-2222-2222-222222222222"},
{"iat",iat},
{"exp",exp},
{"accounttype","serviceA"}
};
//需要通过pem实例化[RS256算法,需要实例化RSAParameters ]
RSACryptoServiceProvider privateKey;
string path=HttpContext.Current.Server.MapPath("~/"+"test-pri.pem");
StreamReader reader =new StreamReader(path);
PemReader pemReader = new PemReader(reader);
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
RSAParameters rsaParameters=DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private);
privateKey = new RSACryptoServiceProvider();
privateKey.ImportParameters(rsaParameters);
var token=Jose.JWT.Encode(claims,privateKey,Jose.JwsAlgorithm.RS256,extraHeaders:headers);
return token;
}
这篇关于(C#语言) httpClient使用put方式提交multiparty/form-data 数据类型 的 csv格式的文件【bear token鉴权】的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具