JAVA模拟HTTP post请求上传图片
生活随笔
收集整理的這篇文章主要介紹了
JAVA模拟HTTP post请求上传图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
1.原理:實現思路和具體步驟就是模擬頁面的請求
?
/*** @author qimh* @description 模擬form表單,上傳圖片* @param fileName -- 圖片路徑* @return 接口返回的json數據* 原理:模擬form表單提交:把請求頭部信息和和img 信息 寫入到輸出流中,* 通過流把img寫入到服務器臨時目錄里,然后服務器再把img移到指定的位置* 最后通過寫入流來獲取post的響應信息。* */public static void uploadImg(String fileName) { try { // 換行符 final String newLine = "\r\n"; final String boundaryPrefix = "--"; // 定義數據分隔線 String BOUNDARY = "========7d4a6d158c9"; // 服務器的域名 URL url = new URL(ECSheng);//"www.myhost.com",ECSheng=http://192.168.1.59/ecstore/index.php/openapi/syncnovo/image_upload ,即為form的action值HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 設置為POST情 conn.setRequestMethod("POST"); // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // 設置請求頭參數 conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream()); // 上傳文件 File file = new File(fileName); StringBuilder sb = new StringBuilder(); sb.append(boundaryPrefix); sb.append(BOUNDARY); sb.append(newLine); // 文件參數,photo參數名可以隨意修改 sb.append("Content-Disposition: form-data;name=\"upload_item\";filename=\"" + fileName + "\"" + newLine); sb.append("Content-Type:image/jpeg"); // 參數頭設置完以后需要兩個換行,然后才是參數內容 sb.append(newLine); sb.append(newLine); // 將參數頭的數據寫入到輸出流中 out.write(sb.toString().getBytes()); // 數據輸入流,用于讀取文件數據 DataInputStream in = new DataInputStream(new FileInputStream(file)); byte[] bufferOut = new byte[1024]; int bytes = 0; // 每次讀1KB數據,并且將文件數據寫入到輸出流中 while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } // 最后添加換行 out.write(newLine.getBytes()); in.close(); // 定義最后數據分隔線,即--加上BOUNDARY再加上--。 byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine) .getBytes(); // 寫上結尾標識 out.write(end_data); out.flush(); out.close(); // 定義BufferedReader輸入流來讀取URL的響應 ----讀取返回的結果BufferedReader reader = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { // System.out.println(line); JSONObject jsonObject = new JSONObject(line);//創建jsonObjec對象String json = jsonObject.toString();//josn格式的字符串System.out.println(json); } } catch (Exception e) { System.out.println("發送POST請求出現異常!" + e); e.printStackTrace(); } }參考鏈接:http://www.cnblogs.com/woolhc/p/6123975.html
? ? ? ? ? ? ? ??
????????????????http://blog.csdn.net/yjclsx/article/details/70675057
轉載于:https://my.oschina.net/qimhkaiyuan/blog/1358229
總結
以上是生活随笔為你收集整理的JAVA模拟HTTP post请求上传图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 切换账户、切换命令行和图形界面
- 下一篇: 选购光端机有哪些必备条件