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 中的解决方案执行完全相同的操作。
最佳答案
我检查过我之前是否使用过这段代码,我不太记得它到底是如何工作的,但在这里:
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;
关于java - 在 Android 中编码多部分表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33364449/