HttpURLConnection模擬post提交form表單

原理是: 分析文件上傳的數(shù)據(jù)格式,然后根據(jù)格式構造相應的發(fā)送給服務器的字符串。
格式如下:這里的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)表示各個數(shù)據(jù)必須以(\r\n)結尾。

下面按照這些數(shù)據(jù)結構進行請求:

 private static final String CONTENT_TYPE = "multipart/form-data"; //內(nèi)容類型
 private static final String BOUNDARY = "FlPm4LpSXsE" ; //定義數(shù)據(jù)分隔符(可以隨意更改) 

創(chuàng)建HttpsURLConnection 連接

 public static HttpsURLConnection getHttpsURLConnectionMul(Context context, String url, String method) {
        URL u;
        HttpsURLConnection connection = null;
        try {        
                u = new URL(url);
                connection = (HttpsURLConnection) u.openConnection();
                connection.setRequestMethod(method);//"POST" "GET"
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);

                connection.setInstanceFollowRedirects(true);
          
                connection.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
//                connection.setRequestProperty("Content-Type", "application/json");
//                connection.setRequestProperty("Content-Type", "multipart/form-data");
                connection.setRequestProperty("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");                   
                connection.setConnectTimeout(10000);
           
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

把數(shù)據(jù)寫入輸出流

DataOutputStream ds = new DataOutputStream(connection.getOutputStream());
addText(your_value1,your_value2,ds);
 private void addText(String file_sum,String json_data,OutputStream output) {
       String lineStart = "--";
       String boundary = "FlPm4LpSXsE";    // 數(shù)據(jù)分隔符
       String lineEnd ="\r\n";

       StringBuilder sb = new StringBuilder();
       sb.append(lineStart  + boundary + lineEnd);
       sb.append("Content-Disposition: form-data; name=\"your_key1\"" + lineEnd);
       sb.append(lineEnd);
       sb.append(your_value1+ lineEnd);
       sb.append(lineStart + boundary + lineEnd);
       sb.append("Content-Disposition: form-data; name=\"your_key2\"" + lineEnd);
       sb.append(lineEnd);
       sb.append(your_value2+ lineEnd);
       String ss = "\r\n--" + boundary + "--\r\n";
       sb.append(ss);
       try {
           Log.e(TAG,"上傳的表單數(shù)據(jù):   " + sb.toString());
           output.write(sb.toString().getBytes("utf-8"),0,sb.toString().getBytes("utf-8").length);// 發(fā)送表單字段數(shù)據(jù)
           output.flush();
           output.close();
       } catch (IOException e) {
           Log.e(TAG,"上傳的表單數(shù)據(jù)寫入異常:   " + e.getCause());
           throw new RuntimeException(e);
       }
   }

遇到的坑:

因為我創(chuàng)建 HttpsURLConnection 所定義數(shù)據(jù)分隔符 和寫入DataOutputStream里的所定義的數(shù)據(jù)分隔符不一致,導致服務端接收不到數(shù)據(jù)

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 第5章 引用類型(返回首頁) 本章內(nèi)容 使用對象 創(chuàng)建并操作數(shù)組 理解基本的JavaScript類型 使用基本類型...
    大學一百閱讀 3,679評論 0 4
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評論 19 139
  • 三年前看到這本書的推薦,毫不猶豫把它收入囊中。對一個循規(guī)蹈矩工作生活著,盼望著所有假期出發(fā)旅行的人來說,有相...
    Clearness閱讀 520評論 0 0
  • Hi,我叫一一,今年十八歲,我是一名師范類在校大學生,當初選擇讀這個專業(yè),并非我本意。 只不過家人都說為我好,說女...
    372a44c29777閱讀 270評論 4 1
  • 35歲 你因為身體越來越差 加班越來越少 晉升的速度也越來越緩慢 那天下班,媳婦告訴你 孩子要上幼兒園了 雙語的一...
    徐阿來閱讀 483評論 0 2

友情鏈接更多精彩內(nèi)容