5
这是我第一次发送多部分请求,在挖掘完成后,我变得更加困惑,所以任何关于“正确”方式的帮助都会非常有用。如何在java中使用HttpURLConnection发送多部分POST请求?
我有一个函数,应该得到:文件路径和JSON的字符串表示,并使用multipart向服务器发送POST请求。
我不知道何时使用boundary
和"multipart/form-data"
内容类型和addPart
和addTextBody
,当(或原因)之间的差异也总是被写入Content-Disposition: form-data; name=\
public String foo(String filePath, String jsonRep, Proxy proxy)
{
File f = new File(filePath);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection(proxy);
connection.setRequestProperty("Content-Type", "multipart/form-data"); // How should I generate boundary? Should it be added here?
if (myMethod == "POST")
{
connection.getOutputStream().write(? Both the json string and the file bytes??);
}
.... checking there is no error code etc..
return ReadResponse(connection) // read input stream..
现在我不知道如何继续下去,以及如何编写的文件和JSON字符串 我看到这个代码:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
builder.addPart("text1", stringBody1);
builder.addPart("text2", stringBody2);
但我似乎无法理解如何将它连接到我的connection
。
你能帮忙吗?
也就是说exacly我的问题。我找不到有关使用MultipartEntityBuilder和HttpURLConnection的更多信息。 – 2015-07-28 01:16:41