藍信上傳附件接口調用(JAVA)

 

上傳附件接口說明(https://docs.lanxin.cn/base.html#nav3-2-1

 

步驟html

1.  定義數據分隔線boundary( 長度建議10位以上 )
2.  與微/藍信服務器創建鏈接(HttpURLConnection)
3.  獲取要上傳的文件輸出流,構造請求體等相關參數開始向微/藍信服務器寫數據(form-data中媒體文件標識,有filename、filelength、content-type等信息,其中file的表單名稱爲media )。
4. 上傳文件後讀取微/藍信服務器返回的內容,並解析爲json格式返回(定義BufferedReader輸入流來讀取URL的響應)java

方案一(JAVA代碼)

(適用於微信和藍信)json

/**  * 上傳藍信附件 * @param accessToken * @param filename * @return
     */
    public JSONObject uploadMedia(String accessToken,String filename) { JSONObject jsonObject = null;         String UPLOAD_WECHAT_URL = "https://login.lanxin.cn/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"; String last_lanx_url = UPLOAD_WECHAT_URL.replace("ACCESS_TOKEN", accessToken); // 定義數據分割符
                String boundary = "----------sunlight"; //                
                try { File file=new File(filename); // URL url = new URL(last_lanx_url);
                    URL url = new URL(null,last_lanx_url,new sun.net.www.protocol.https.Handler()); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); //發送POST請求必須設置以下兩行
                    conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream out = new DataOutputStream(conn.getOutputStream()); byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();// 定義最後數據分隔線
                    StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(boundary); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes(); out.write(data); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024 * 8]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write("\r\n".getBytes()); // 多個文件時,二個文件之間加入這個
 in.close(); out.write(end_data); out.flush(); out.close(); // 定義BufferedReader輸入流來讀取URL的響應
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(line); } System.out.println("請求藍信上傳附件接口響應報文內容爲:"+buffer.toString()); jsonObject = JSONObject.parseObject(buffer.toString()); } catch (Exception e) { System.out.println("POST請求藍信上傳附件接口出現異常");
            e.printStackTrace();
return null; } return jsonObject; }
 

方案二 (JAVA代碼)

(適用於微信/藍信)api

import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import net.sf.json.JSONObject; public class WXUpload { private static final String upload_wechat_url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"; public static JSONObject upload(String accessToken, String type, File file) { JSONObject jsonObject = null; String last_wechat_url = upload_wechat_url.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type); // 定義數據分割符
        String boundary = "----------sunlight"; try { URL uploadUrl = new URL(last_wechat_url); HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection(); uploadConn.setDoOutput(true); uploadConn.setDoInput(true); uploadConn.setRequestMethod("POST"); // 設置請求頭Content-Type
            uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); // 獲取媒體文件上傳的輸出流(往微信服務器寫數據)
            OutputStream outputStream = uploadConn.getOutputStream(); // 從請求頭中獲取內容類型
            String contentType = "Content-Type: " + getContentType(); // 請求體開始
            outputStream.write(("--" + boundary + "\r\n").getBytes()); outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName()).getBytes()); outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes()); // 獲取媒體文件的輸入流(讀取文件)
            DataInputStream in = new DataInputStream(new FileInputStream(file)); byte[] buf = new byte[1024 * 8]; int size = 0; while ((size = in.read(buf)) != -1) { // 將媒體文件寫到輸出流(往微信服務器寫數據)
                outputStream.write(buf, 0, size); } // 請求體結束
            outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes()); outputStream.close(); in.close(); // 獲取媒體文件上傳的輸入流(從微信服務器讀數據)
            InputStream inputStream = uploadConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuffer buffer = new StringBuffer(); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 釋放資源
 inputStream.close(); inputStream = null; uploadConn.disconnect(); // 使用json解析
            jsonObject = JSONObject.fromObject(buffer.toString()); System.out.println(jsonObject); } catch (Exception e) { System.out.println("上傳文件失敗!"); e.printStackTrace(); } return jsonObject; } // 獲取文件的上傳類型,圖片格式爲image/png,image/jpeg等。非圖片爲application /octet-stream
    private static String getContentType() throws Exception { return "application/octet-stream"; } }

 

 

參考地址 https://blog.csdn.net/omsvip/article/details/41350063服務器

相關文章
相關標籤/搜索