因为工作的需要,需要用java调c#写好的webapi接口来实现跨语言的文件的传输,话不多说,直接上代码

一:Java的代码(相当于客户端):

  

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
public class http {
public static Map<String,Object> uploadFileByHTTP(File postFile,String postUrl,Map<String,String> postParam){
//Logger log = LoggerFactory.getLogger(UploadTest.class);

Map<String,Object> resultMap = new HashMap<String,Object>();
CloseableHttpClient httpClient = HttpClients.createDefault();
try{
//把一个普通参数和文件上传给下面这个地址 是一个servlet
HttpPost httpPost = new HttpPost(postUrl);
//把文件转换成流对象FileBody
FileBody fundFileBin = new FileBody(postFile);
//设置传输参数
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
//multipartEntity.setCharset(Charset.forName("GB2312"));
//multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
String fileCode=(String)System.getProperties().get("file.encoding");
String filename = postFile.getName();
//filename= new String (filename.getBytes(fileCode),fileCode);
String name=gbEncoding(filename); //需要将文件名unicode来传送,以防乱码
multipartEntity.addPart(name, fundFileBin);
//multipartEntity.addPart(postFile.getName(), fundFileBin);//相当于<input type="file" name="media"/>//multipartEntity.addPart(postFile.getName(), fundFileBin);//相当于<input type="file" name="media"/>

//设计文件以外的参数
Set<String> keySet = postParam.keySet();
for (String key : keySet) {
//相当于<input type="text" name="name" value=name>
multipartEntity.addPart(key, new StringBody(postParam.get(key), ContentType.create("application/json", Consts.UTF_8)));//application/json
}

HttpEntity reqEntity = multipartEntity.build();

httpPost.setEntity(reqEntity);

//log.info("发起请求的页面地址 " + httpPost.getRequestLine());
//发起请求 并返回请求的响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
///log.info("----------------------------------------");
//打印响应状态
//log.info(response.getStatusLine());
resultMap.put("statusCode", response.getStatusLine().getStatusCode());
//获取响应对象
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
//打印响应长度
//log.info("Response content length: " + resEntity.getContentLength());
//打印响应内容
resultMap.put("data", EntityUtils.toString(resEntity,Charset.forName("UTF-8")));
}
//销毁
EntityUtils.consume(resEntity);
} catch (Exception e) {
e.printStackTrace();
} finally {
response.close();
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally{
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//log.info("uploadFileByHTTP result:"+resultMap);
return resultMap;
}



public static String gbEncoding(final String gbString) { //将中文转unicode
char[] utfBytes = gbString.toCharArray();
String unicodeBytes = "";
for (int i = 0; i < utfBytes.length; i++) {
String hexB = Integer.toHexString(utfBytes[i]);
if (hexB.length() <= 2) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "\\u" + hexB;
}
return unicodeBytes;
}

//测试
public static void main(String args[]) throws Exception {
//要上传的文件的路径
String filePath = "C:\\Users\\LYY\\Desktop\\xml\\自动化生产线2.xml";
String postUrl = "http://localhost:8081/api/Trading/Files/Test"; //服务器的路径
Map<String,String> postParam = new HashMap<String,String>();
postParam.put("methodsName", "Saw");
postParam.put("serverPath", "Saw");
postParam.put("ArtifactsNum", "0");
postParam.put("userName", "finchina");
postParam.put("guidStr", "7b2c7a31-ca59-46c5-9290-6b4303498e5e");
postParam.put("routeUrl", "http://120.76.96.61:8085/");

File postFile = new File(filePath);
Map<String,Object> resultMap = uploadFileByHTTP(postFile,postUrl,postParam);
System.out.println(resultMap);
}
}

二:c#的webapi的接口代码(服务端):文件的接收

  


      
 //将unicode转为中文
        public static string Unicode2String(string source)
        {
            return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
                source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
        }
        [HttpPost]
        public IHttpActionResult AcceptPost()
        {
          
            string result = "";
            string url = "";
            List<Stream> listStream = new List<Stream>();
            List<byte[]> listContentByte = new List<byte[]>();
            List<string> listFileName = new List<string>();           
            string methodsName = System.Web.HttpContext.Current.Request.Form["methodsName"];
            string serverPath = System.Web.HttpContext.Current.Request.Form["serverPath"];
            string ArtifactsNum = System.Web.HttpContext.Current.Request.Form["ArtifactsNum"];
            string userName = System.Web.HttpContext.Current.Request.Form["userName"];
            string guidStr = System.Web.HttpContext.Current.Request.Form["guidStr"];
            string routeUrl = System.Web.HttpContext.Current.Request.Form["routeUrl"];
            FilesType filesType = FilesType.General;
            HttpFileCollection Files = HttpContext.Current.Request.Files;
            string[] allkeys = Files.AllKeys;
            for (int i = 0; i < allkeys.Length; i++)
            {
                string filekey = allkeys[i];
                string name = Unicode2String(filekey);
                string[] namearr = name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                string filename = string.Join("", namearr);
                listFileName.Add(filename);
            }
            HttpContext context = HttpContext.Current;
            for (int i = 0; i < context.Request.Files.Count; i++)
            {
                try
                {
                    HttpPostedFile aFile = context.Request.Files[i];
                    Stream mystream = aFile.InputStream;
                    StreamReader reader = new StreamReader(mystream);
                    string xml = " ";
                    StringBuilder strXML = new StringBuilder();
                    while (reader.Peek() >= 0)
                    {
                        string line = reader.ReadLine().Trim();//直接读取一行
                        if (line == null) return null;
                        if (line == String.Empty) continue;
                        if (line.StartsWith("<"))
                        {
                            xml = line.Trim();
                            strXML.Append(xml);
                        }
                    }
                    String xmlData = reader.ReadToEnd();
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strXML.ToString());
                    listContentByte.Add(bytes);
                }
                catch
                {
                }
            }
            //接收传递过来的数据流
            /*Stream stream = System.Web.HttpContext.Current.Request.InputStream;
            StreamReader reader = new StreamReader(stream);       
            string xml = " ";
            StringBuilder strXML = new StringBuilder();
            string[] heads = HttpContext.Current.Request.Headers.AllKeys;
            string headvalues = HttpContext.Current.Request.Headers.ToString();
            while (reader.Peek() >= 0)
            {
                string line = reader.ReadLine().Trim();//直接读取一行
                if (line == null) return null;
                if (line == String.Empty) continue;
                if (line.StartsWith("<"))
                {
                    xml = line.Trim();
                    strXML.Append(xml);
                }
            }
            String xmlData = reader.ReadToEnd();         
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strXML.ToString());          
            listContentByte.Add(bytes); */
            using (HttpClient client = new HttpClient())
            {
                Dictionary<string, string> DicData = new Dictionary<string, string>();
                DicData.Add("MethodName", methodsName);
                DicData.Add("ServerPath", serverPath);
                DicData.Add("ArtifactsNum", ArtifactsNum.ToString());
                DicData.Add("SendTime", DateTime.Now.ToString());
                DicData.Add("UserName", userName);
                DicData.Add("FileType", filesType.ToString());
                DicData.Add("FileGuid", guidStr);
                client.MaxResponseContentBufferSize = 2147483647;
                client.Timeout = TimeSpan.FromMinutes(30);
                MediaTypeWithQualityHeaderValue temp = new MediaTypeWithQualityHeaderValue("application/json") { CharSet = "utf-8" };
                client.DefaultRequestHeaders.Accept.Add(temp);//设定要响应的数据格式
                using (var content = new MultipartFormDataContent())//表明是通过multipart/form-data的方式上传数据
                {
                    var formDatas = this.GetFormDataByteArrayContent(this.GetNameValueCollection(DicData));//获取键值集合对应
                    var files = this.GetFileByteArray(listContentByte, listFileName);//获取文件集合对应的ByteArrayContent集合
                    Action<List<ByteArrayContent>> act = (dataContents) =>
                    {//声明一个委托,该委托的作用就是将ByteArrayContent集合加入到MultipartFormDataContent中
                        foreach (var byteArrayContent in dataContents)
                        {
                            content.Add(byteArrayContent);
                        }
                    };
                    act(formDatas);
                    act(files);//执行act
                    try
                    {
                        url = string.Format(routeUrl + "api/Trading/Files/UploadOptimizeFile");
                        var returnResult = client.PostAsync(url, content).Result;//post请求  
                        if (returnResult.StatusCode == HttpStatusCode.OK)
                            result = returnResult.Content.ReadAsAsync<string>().Result;
                        else
                            result = "30|客户端连接路由端出错,错误代码:" + returnResult.StatusCode.ToString();
                    }
                    catch (Exception ex)
                    {
                        result = "29|客户端连接超时";
                    }
                }
            }
            return Ok(result);
        }
        /// <summary>
        /// 转换成ByteArrayContent列表
        /// </summary>
        /// <param name="listByte">字节数组列表</param>
        /// <param name="listName">对应字节数组的文件名</param>
        /// <returns></returns>
        private List<ByteArrayContent> GetFileByteArray(List<byte[]> listByte, List<string> listName)
        {
            List<ByteArrayContent> list = new List<ByteArrayContent>();
            if (listByte != null && listName != null)
            {
                for (int i = 0; i < listByte.Count; i++)
                {
                    var fileContent = new ByteArrayContent(listByte[i]);
                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = listName[i]
                    };
                    list.Add(fileContent);
                }
            }
            return list;
        }