1. 程式人生 > 實用技巧 >java伺服器間http通訊,同時傳輸檔案流和資料,並接收返回的檔案流或資料

java伺服器間http通訊,同時傳輸檔案流和資料,並接收返回的檔案流或資料

廢話:這裡使用的是HttpUrlConnection,httpclient沒有試過,這篇文章也是收集了很多大佬的成果,但是由於太久遠了找不到原文了,如果有大佬看到提醒一下,願意貼上原文連結的哈,抱歉抱歉,現在實現了同時傳輸檔案和資料,但是response返回的檔案和資料只能接收一個,如果大家有同時接收的方法,望告知,謝謝大家了。

需求:其實就是伺服器間通過http進行通訊,不走前端的那種,公司需求給某個網址主動發文件流,並且接收response中的反饋檔案流或者錯誤資訊。

連線工具類HttpUrlConnection.java,現在支援傳多個數據,一個檔案,如果需要多個檔案,照著改改應該沒問題的

@Component
public class HttpUrlConnection {

    //頭部格式
    private static final String nextLine = "\r\n";
    private static final String twoHyphens = "--";
    //隨便寫一個
    private static final String boundary = java.util.UUID.randomUUID().toString();

    /**
     * @Description:java專案的服務端之間的通訊
     * @Param: [requestUrl,請求url
     * jsessionId, 瀏覽器的訪問的Cookie,即被訪問的服務端的session。若被訪問的伺服器沒有做url過濾器,則該引數可以為null。
     * file, 傳送出去的檔案
     * feedbackFile, 收到的反饋檔案存放位置
     * name,對方用來接收檔案的名字
     * params,要傳的引數
     * @Return: java.util.Map
     * @Author: Liting
     * @Date: 2019-11-26 08:54
     
*/ public static Map httpUrlConnection(String requestUrl, String jsessionId, File file, String feedbackFile, String name, Map<String,String> params) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(requestUrl).openConnection(); if (!Utils.isEmpty(jsessionId)) { con.setRequestProperty(
"Cookie", "JSESSIONID=" + jsessionId); } // 設定是否向httpUrlConnection輸出,因為這個是post請求,引數要放在 // http正文內,因此需要設為true, 預設情況下是false; con.setDoOutput(true); // 設定是否從httpUrlConnection讀入,預設情況下是true; con.setDoInput(true); // 設定請求的方法為"POST",預設是GET con.setRequestMethod("POST"); // Post 請求不能使用快取 con.setUseCaches(false); //設定接收返回值的格式 con.setRequestProperty("Accept", "text/plain, */*"); //設定接收編碼 con.setRequestProperty("Accept-Language", "zh-cn"); con.setRequestProperty("Host","127.0.0.1"); //設定請求引數格式以及boundary分割線 con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); con.setRequestProperty("User-Agent"," WinHttpClient"); //開啟長連線可以持續傳輸 con.setRequestProperty("Connection", "Keep-Alive");
     //連線超時時間20秒 con.setConnectTimeout(
20000);
     //讀取超時時間20秒 con.setReadTimeout(
20000); OutputStream out = con.getOutputStream(); //分隔符頭部 //拼接引數 if (!Utils.isEmpty(params)){ int i = 0; for (String paramName : params.keySet()){ StringBuffer strBufparam = new StringBuffer(); strBufparam.append(twoHyphens); strBufparam.append(boundary); strBufparam.append(nextLine); strBufparam.append("Content-Disposition: form-data;name=\""+paramName+"\""); strBufparam.append(nextLine); strBufparam.append("Content-Type: " + "text/plain"); strBufparam.append(nextLine); strBufparam.append("Content-Length: " + params.get(paramName).getBytes().length); strBufparam.append(nextLine); strBufparam.append(nextLine); strBufparam.append(params.get(paramName)); i++; if (i!=params.size()){ strBufparam.append(nextLine); } out.write(strBufparam.toString().getBytes()); } } //拼接檔案 if (!Utils.isEmpty(file)){ StringBuffer strBufFile = new StringBuffer(); strBufFile.append(nextLine); strBufFile.append(twoHyphens); strBufFile.append(boundary); strBufFile.append(nextLine); strBufFile.append("Content-Disposition: form-data; name=\""+name+"\"; filename=\"" + file.getName() + "\""); strBufFile.append(nextLine); strBufFile.append("Content-Type: " + "application/x-tar"); strBufFile.append(nextLine); strBufFile.append("Content-Length: " + file.length()); strBufFile.append(nextLine); strBufFile.append(nextLine); //寫入輸出流 out.write(strBufFile.toString().getBytes()); //讀取本地檔案流 FileInputStream inputStream = new FileInputStream(file); byte[] data = new byte[2048]; int len = 0; int sum = 0; while ((len = inputStream.read(data)) != -1) { //將讀取到的本地檔案流讀取到HttpsURLConnection,進行上傳 out.write(data, 0, len); sum = len + sum; } //檔案寫入完成後加回車 out.write(nextLine.getBytes()); inputStream.close(); } //寫入結束分隔符 String footer = nextLine + twoHyphens + boundary + twoHyphens + nextLine; out.write(footer.getBytes()); out.flush(); out.close(); con.connect(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { if (!Utils.isEmpty(feedbackFile)) {//有返回檔案的時候 String fileName = ""; try { fileName = con.getHeaderField(1).substring(21, con.getHeaderField(1).length() - 1); fileName = "EBDT"+fileName.split("_")[1]; System.out.println(fileName); }catch (Exception e){ return null; } BufferedInputStream in = new BufferedInputStream(con.getInputStream()); File f = new File(feedbackFile); if (!f.exists()) { f.mkdirs(); } File res = new File(feedbackFile+"/"+fileName); FileOutputStream fos = new FileOutputStream(res); byte[] by = new byte[1024]; int length = 0; while ((length = in.read(by)) != -1) { fos.write(by, 0, length); } fos.close(); in.close(); con.disconnect(); if (Utils.isEmpty(fos)) { return null; } //處理接收到的檔案 //儲存到本地 Map map = new HashMap(); map.put("fileName",fileName); return map; }else{ //接收到的return中的值 BufferedReader br = new BufferedReader(new InputStreamReader( con.getInputStream())); String s = br.readLine(); br.close(); con.disconnect(); try{ if (!Utils.isEmpty(s)){ Object m = JSONObject.parse(s); Map map = (Map) m; return map; } }catch (Exception e){ Map map = new HashMap(); map.put("feedback",s); return map; } } return new HashMap(); } else { con.disconnect(); return null; } } }

main方法測試

public static void main(String[] args) throws IOException {
        Map<String,String> map = new HashMap<>();
        map.put("name","張三");
        map.put("age","23");
        File file = new File("D:\\1.xml");
        Map map1 = HttpUrlConnection.httpUrlConnection("http://127.0.0.1/user/addUser", "69e4baee-ff22-4cdf-a73b-6156c5d6d2c1", file, "",
                "files", map);
        System.out.println(map1);
    }

結果

到這就是全部了,如有問題歡迎留言