【问题标题】:Encoding multipart form data in Android在 Android 中编码多部分表单数据
【发布时间】:2015-10-27 09:42:42
【问题描述】:

而 Python 有一个非常标准的代码用于发送多部分形式的数据,或者更确切地说,对其进行编码:

def encode_multipart_formdata(fields, files):
  # fields is a sequence of (name, value) elements for regular form fields.
  # files is a sequence of (name, filename, value) elements for data to be uploaded as files
  # Return (content_type, body) ready for httplib.HTTP instance
  BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
  CRLF = '\r\n'
  L = []
  for (key, value) in fields:
    L.append('--' + BOUNDARY)
    L.append('Content-Disposition: form-data; name="%s"' % key)
    L.append('')
    L.append(value)
  for (key, filename, value) in files:
    L.append('--' + BOUNDARY)
    L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
    L.append('Content-Type: %s' % get_content_type(filename))
    L.append('')
    L.append(value)
  L.append('--' + BOUNDARY + '--')
  L.append('')
  body = CRLF.join(L)
  content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
  return content_type, body

我想知道,我怎样才能在 Android 中做同样的事情,对多部分表单数据进行编码?

我找到了一些解决方案,但它们都不应该在 python 中做与这个完全相同的事情。

【问题讨论】:

标签: java android python http-post


【解决方案1】:

我检查过我以前是否使用过这段代码,我真的不记得它是如何工作的,但在这里:

    HttpURLConnection conn = null;
    DataOutputStream dOut = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";

      URL url = new URL("http://shrimptalusan.hostei.com/usbong/build-upload.php");

      conn = (HttpURLConnection) url.openConnection();
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setUseCaches(false);

设置多部分表单的开头:

      conn.setRequestMethod("POST");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setRequestProperty("ENCTYPE", "multipart/form-data");
      conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
      conn.setRequestProperty("utreeFile", utreeFilePath);

      dOut = new DataOutputStream(conn.getOutputStream());
      dOut.writeBytes(twoHyphens + boundary + lineEnd);
      dOut.writeBytes("Content-Disposition: form-data; name=\"utreeFile\";filename=\"" + utreeFilePath + "\"" + lineEnd);
      dOut.writeBytes(lineEnd);

      bytesAvailable = utreeFileIn.available();
      bufferSize = Math.min(bytesAvailable, maxBuffersize);
      buffer = new byte[bufferSize];
      bytesRead = utreeFileIn.read(buffer, 0, bufferSize);

将文件读入缓冲区:

      while (bytesRead > 0) {
          progress += bytesRead;
          dOut.write(buffer, 0, bufferSize);
          bytesAvailable = utreeFileIn.available();
          publishProgress((int) ((progress * 100) / (utreeFile.length())));
          bufferSize = Math.min(bytesAvailable, maxBuffersize);
          buffer = new byte[bufferSize]; //TEST
          bytesRead = utreeFileIn.read(buffer, 0, bufferSize);
      }

要包含在多部分实体中的附加参数:

      //PARAMETER FIELD NAME
      dOut.writeBytes(twoHyphens + boundary + lineEnd);
      dOut.writeBytes("Content-Disposition: form-data; name=\"youtubelink\"" + lineEnd);
      dOut.writeBytes(lineEnd);
      dOut.writeBytes(youtubeLink); // mobile_no is String variable
      dOut.writeBytes(lineEnd);
      //PARAMETER END

结束多部分:

      dOut.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

通过 HTTP 发送多部分:

      if (conn.getResponseCode() != HttpsURLConnection.HTTP_OK) {
          utreeFileIn.close();
          throw new RuntimeException("Failed : HTTP error code : "
                  + conn.getResponseCode());
      } else {
          BufferedReader br = new BufferedReader(new InputStreamReader(
                  (conn.getInputStream())));
          String line;
          while ((line = br.readLine()) != null) {
              System.out.println(line);
              responseString += line;
          }
      }

关闭文件和连接:

    utreeFileIn.close();
    dOut.flush();
    dOut.close();

希望它能给你一个更好的主意。我认为我没有使用任何外部库。这是我的导入:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

【讨论】:

  • 非常感谢,让我试试。它是否也适用于普通 http(不适用于 https)?
  • utreeFileIn 的类型是什么?
  • @JennyT。是的,它应该仍然适用于 https。 utreeFileIn 是 FileInputStream utreeFileIn = new FileInputStream(pathToFile);它可以是任何文件(zip、jpeg 等...)
猜你喜欢
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
  • 2019-08-01
  • 2010-11-24
相关资源
最近更新 更多