问题遇到的现象和发生背景
公司要调用一个JAVA的文件上传接口,并接收返回值。给的示例代码是JAVA的,但项目使用C#编写,我对JAVA也是一窍不通,JAVA的类和方法也看不太明白。麻烦各位谁能帮我把JAVA的示例代码翻译一个C#功能相同吗。万分感谢
用代码块功能插入代码,请勿粘贴截图
JAVA示例:
public class MainUI {
public static void main(String[] args) throws Exception {
// 企业 id
String enterpriseId = "xxxxxx";
// 加密后的时间戳
String token =
"N+zE3m6KpyRbIwKMZlwuXvRYg7gW368PhJE/iuOHq5H3BhH/57iQ7p7ICiRzua0tYydLxbRZH4Rj3qDz7fkaBhT
G9eQ6V6+zwDEDK68E8AD9/gQUuU6ViI6pLk6eyTzzKRMWJc0NZoUIGg7sPGkhBfVhUl7ortHNLSB+FJxzFEg=";
String url = "http://xxxxx/merchandise/uploadReport";
File file = new File("/Users/zhangwenbin/Documents/测试.pdf");
FileInputStream inputStream = new FileInputStream(file);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", inputStream, ContentType.MULTIPART_FORM_DATA, "
测试.pdf")
.addTextBody("token", token)
.addTextBody("enterpriseId", enterpriseId);
httpPost.setEntity(builder.build());
// 获取响应内容
HttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200){
if (null != response.getEntity()) {
// 将响应内容转换为字符串
String json = EntityUtils.toString(response.getEntity(),
Charset.forName("UTF-8"));
JSONObject responseJson = JSON.parseObject(json);
Boolean isSuccess = (Boolean) responseJson.get("success");
if(isSuccess){
JSONObject module = (JSONObject) responseJson.get("module");
String key = (String) module.get("key");
System.out.println(module.toJSONString());
}
}
}
} }
我的解答思路和尝试过的方法
我自己用C#的MultipartFormDataContent凭着猜测模拟的代码
///
/// 上传file到接口
///
/// <param name="url"></param>
/// <param name="fileName"></param>
/// <param name="filePath"></param>
/// <param name="EnterpriseId"></param>
/// <returns></returns>
private string RequestFilePost(string url, string fileName, string filePath,string EnterpriseId)
{
try
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
var timeStamp = Convert.ToInt64(ts.TotalMilliseconds).ToString();
string token = RasEncrypt(timeStamp, PUBLIC_KEY);
//1
var postContent = new MultipartFormDataContent();
postContent.Headers.Add("ContentType", $"multipart/form-data");
postContent.Add(new StringContent(token), "token");
postContent.Add(new StringContent(EnterpriseId), "enterpriseId");
postContent.Add(new ByteArrayContent(File.ReadAllBytes(filePath)), "file");
string result = "";
try
{
HttpClient client = new HttpClient();
HttpResponseMessage response1 = client.PostAsync(url, postContent).Result;
result = response1.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
}
我想要达到的结果
根据JAVA示例弄一个C#功能相同的方法。