HttpURLConnection模拟post提交form表单

原理是: 分析文件上传的数据格式,然后根据格式构造相应的发送给服务器的字符串。
格式如下:这里的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)结尾。

下面按照这些数据结构进行请求:

 private static final String CONTENT_TYPE = "multipart/form-data"; //内容类型
 private static final String BOUNDARY = "FlPm4LpSXsE" ; //定义数据分隔符(可以随意更改) 

创建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;
    }

把数据写入输出流

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";    // 数据分隔符
       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,"上传的表单数据:   " + sb.toString());
           output.write(sb.toString().getBytes("utf-8"),0,sb.toString().getBytes("utf-8").length);// 发送表单字段数据
           output.flush();
           output.close();
       } catch (IOException e) {
           Log.e(TAG,"上传的表单数据写入异常:   " + e.getCause());
           throw new RuntimeException(e);
       }
   }

遇到的坑:

因为我创建 HttpsURLConnection 所定义数据分隔符 和写入DataOutputStream里的所定义的数据分隔符不一致,导致服务端接收不到数据

你可能感兴趣的:(HttpURLConnection模拟post提交form表单)