公司要调用一个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到接口
///
///
///
///
///
///
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#功能相同的方法。
已解决。我特意问了一下我们专门弄JAVA的同事。CloseableHttpClient 这玩意就是一个自带关闭的HttpClicent。还有builder.addBinaryBody("file", inputStream, ContentType.MULTIPART_FORM_DATA, "测试.pdf").addTextBody("token", token).addTextBody("enterpriseId", enterpriseId);这玩意的意思,就是模拟一个form的file文件流加token和enterpriseId提交key-value对。所以我写的C#代码正常就完全没问题。于是跟接口那边沟通,是接口那边出的问题。我也是醉了。。。
看代码功能不难,就是打开文件流,然后通过http发送post请求给服务端,再接收回应,将key值打印出来
具体实现可参考C#post上传文件,post发送文件(Http Post),带其他参数_程序猿够钟的博客-CSDN博客_c# post 发送文件
string postData = "参数"; // 要发放的数据
string postUrl = "地址";
byte[] byteArray = Encoding.Default.GetBytes(postData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
this.Label1.Text = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close();