1. 程式人生 > >android http通過post上傳檔案和提交引數(通過拼裝協議)

android http通過post上傳檔案和提交引數(通過拼裝協議)

HttpURLConnection conn = null;

DataOutputStream outStream = null;
try{
           String BOUNDARY = "---------------------------7da2137580612";    //資料分界線
           
           String MULTIPART_FORM_DATA ="multipart/form-data";
           
           URL url = new URL(Const.URL);
           
               //上傳表單的檔案
               StringBuilder emailSB = new StringBuilder();
               emailSB.append("--");
               emailSB.append(BOUNDARY);
               emailSB.append("\r\n");
               emailSB.append("Content-Disposition:form-data;name=\"email\"\r\n\r\n
");
               emailSB.append(email);
               emailSB.append("\r\n");
               
               StringBuilder bitmapSB = new StringBuilder();
               bitmapSB.append("--");
               bitmapSB.append(BOUNDARY);
               bitmapSB.append("\r\n");
               bitmapSB.append("Content-Disposition:form-data;name=\"image\";filename=\"image\"\r\n");
               bitmapSB.append("Content-Type:image/png\r\n\r\n
");
               
               byte[] end_data =("--"+BOUNDARY+"--\r\n").getBytes();//資料結束標誌
               
               File file = new File("/mnt/sdcard/111.png");
               FileInputStream fileIS = new FileInputStream(file);
               
               long contentLenght = emailSB.toString().getBytes().length +  end_data.length
               + bitmapSB.toString().getBytes().length + file.length() + "\r\n".getBytes().length;
               
               conn = (HttpURLConnection)url.openConnection();
               conn.setDoInput(true);        //允許輸入
               conn.setDoOutput(true);        //允許輸出
               conn.setUseCaches(false);    //不使用caches
               conn.setRequestMethod("POST");
               conn.setRequestProperty("Connection","Keep-Alive");
               conn.setRequestProperty("Content-Type",MULTIPART_FORM_DATA+";boundary="+BOUNDARY);
               conn.setRequestProperty("Content-Length",Long.toString(contentLenght));
               
               
               outStream = new DataOutputStream(conn.getOutputStream());  
               
               outStream.write(emailSB.toString().getBytes());
               
               outStream.write(bitmapSB.toString().getBytes());
               
               byte[] buffer = new byte[1024];
               int len = 0;
               while((len = fileIS.read(buffer)) != -1){
               outStream.write(buffer, 0, len);
               }
               outStream.write("\r\n".getBytes());
               
               
               outStream.write(end_data);            
               outStream.flush();
               int cah = conn.getResponseCode();
               if(cah!=200){
               System.out.println("上傳失敗");
               return;
               }
               InputStream is = conn.getInputStream();
               int ch;
               StringBuilder result = new StringBuilder();
               while((ch=is.read())!=-1){
               result.append((char)ch);
               }
               System.out.println("result :" + result.toString());
           } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
       finally{
        try {
        if(outStream != null){
        outStream.close();
        }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        if(conn != null){
        conn.disconnect();
        conn = null;
        }

       }

使用HttpUrlConnection模擬post表單進行檔案上傳平時很少使用,比較麻煩。

原理是: 分析檔案上傳的資料格式,然後根據格式構造相應的傳送給伺服器的字串。

格式如下:這裡的httppost123是我自己構造的字串,可以是其他任何的字串

----------httppost123 (\r\n)
Content-Disposition: form-data; name="img"; filename="t.txt" (\r\n)
Content-Type: application/octet-stream (\r\n)

(\r\n)

sdfsdfsdfsdfsdf (\r\n)
----------httppost123 (\r\n)
Content-Disposition: form-data; name="text" (\r\n)

(\r\n)

text tttt (\r\n)
----------httppost123-- (\r\n)
(\r\n)

上面的(\r\n)表示各個資料必須以(\r\n)結尾。



相關推薦

android http通過post檔案提交引數通過協議

HttpURLConnection conn = null; DataOutputStream outStream = null;try{           String BOUNDARY = "---------------------------7da2137580

HttpClient通過post檔案提交引數

       //new一個DiskFileItemFactory型別的物件factory(檔案工廠)                   DiskFileItemFactory factory = new DiskFileItemFactory();                   //為factory

Httpclient 以multipart/form-data形式post檔案提交引數

在大學裡由於要做某些英語聽力作業,是在PC客戶端上的,而做完提交後顯示的答案又沒辦法複製,再重新填寫的話答案就消失了,所以懶得去記,好在答案圖片並不複雜,便想做一個可以識別出圖片中的英文的小軟體。因為我自己並沒有做OCR的經驗,於是我就到網上找可以線上識別文字的網站,找著找著

http使用post檔案時,請求頭主體資訊總結

HEADER:  寫道 ...... Content-Type: multipart/form-data; BODY: Content-type: multipart/form-data, boundary=AaB03x --AaB03x content-d

java、 http模擬post檔案到服務端 模擬form檔案

需求是這樣的: **1,前後端分離,前端對接pc軟體進行檔案同步的介面,後的springboot微服務進行檔案接收和處理。 2,軟體不能直接呼叫微服務的介面進行上傳,只能先走一下前端controller進行轉發過來()。 3,這樣就只能用httpclien

Android OkHttp Post檔案並且攜帶引數

這裡整理一下 OkHttp 的 post 在上傳檔案的同時,也要攜帶請求引數的方法。 使用 OkHttp 版本如下: compile 'com.squareup.okhttp3:okhttp:3.4.1' 程式碼如下: protected void po

使用form表單同時實現檔案提交文字資料

使用form表單同時實現上傳檔案和提交文字資料,此示例中在後臺將檔案上傳到阿里的oss儲存伺服器中 申請oss相關賬號: endpoint = "http://oss-cn-qingdao.aliyuncs.com"; accessKeyId = "key"; accessKeySecret = "secr

HttpURLConnection實現java後臺檔案其他引數

最近在對接某第三方視訊服務商的介面,使用java在後臺呼叫他們的介面。在對接設定封面時遇到一個問題,他們需要對個引數,且有一個引數的型別為file。苦尋半天,果。遂記錄如下。 import java.io.DataOutputStream; import j

JS檔案預覽單張多張

Section1單張上傳和預覽:思路:用<input type="file"/> 觸發onchange事件,取出e.target.files || e.target.dataTransfer.files, 將其轉為window.createObjectURL(fi

okhttp檔案攜帶引數

一個小工具類用來post json字串和檔案上傳並且帶引數外加忽略https證書認證 1 上傳檔案和引數 public class NetWorkUtilsHttps { public static final MediaType JSON = MediaType

.Net使用HttpClient以multipart/form-data形式post檔案及其相關引數

  目錄導航:      前言:      什麼是multipart/form-data請求:      Html上傳圖片按鈕:

檔案動態生成目錄自定義工具類

  public class UploadUtils {   // 方式一:使用用 目錄層級 分離 public static String getPath(String uuidFileName){ // 使用唯一檔名.hashCode();

通過 HTTP POST 檔案到伺服器

2. 上傳之前使用者無法預知上傳檔案的數目. 3. 因為是 ASP.NET 應用, 客戶端可能沒有裝 .NET Framework. 其實,我們知道.如果要跟 IE 端客戶檔案系統互動的話,程式碼必須在客戶端執行. 這個時候我們可以寫一個 Activex 控制元件來實現選擇資料夾和上傳. 一般我們常用兩種方

post請求檔案文字時http格式

服務端通常是根據請求頭(headers)中的 Content-Type 欄位來獲知請求中的訊息主體是用何種方式*編碼*,再對主體進行解析。所以說到 POST 提交資料方案,包含了 Content-Type 和訊息主體編碼方式兩部分。 application

C#中PUTPOST檔案

HttpClient中上傳檔案 上一篇主要是提到了HttpClient幫助類,這次針對於上傳檔案進行補充,僅做記錄 public static string HttpUploadFile(string url, string path) {

關於post請求檔案其它資料

1,背景: 在網上搜索這個問題得到的答案只有上傳檔案的單一上傳方式,並沒有說如果還需要其它請求引數的時候該如何處理。 2,解決方案: 通過append來加入其它請求引數,在上傳的時候還是用data:fromlsdata來上傳 3,相關程式碼: handleUp

http檔案進度監控以及構造multipart/form-data請求

http上傳檔案 html程式碼 <!DOCTYPE html> <html> <head> <meta charset="utf-8">

httpclient通過POST檔案,而不是通過流的形式,並在服務端進行解析(通過httpmime.jar來操作)

1. 首先需要對應的JAR包 匯入 httpmime-4.1.1.jar。 package url; import io.IoStreamUtil; import java.io.File; import java.io.IOException; import jav

在spring boot下如何通過rest 介面 來檔案 下載檔案 到 hadoop hdfs

本文將用程式碼來演示在spring boot裡面,用hadoop client,通過restful API來上傳檔案 和下載檔案 到 hadoop hdfs。 裡面有一些程式碼依賴坑,注意繞行。 前提: 如果你的程式碼在windows上執行,去連線linux上的hado

Android POST檔案

/** * 上傳檔案到伺服器類 *  * @author tom */public class UploadUtil {    private static final String TAG = "uploadFile";    private static final i