java調用c#webapi的接口實現文件上傳


因為工作的需要,需要用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;
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM