要求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;
}