问题描述
我用okhttp是我的HttpClient。我认为这是一个很好的API,但商务部没有那么细致。
如何使用它来使用文件上传一个HTTP POST请求?
市民多节createMultiPart(档案文件){
部件部件=(部分)新Part.Builder()的contentType()车身(新文件(1.png))构建()。
//如何设置的部分叫什么名字?
多部分M =新Multipart.Builder()addPart(部分).build()。
返回米;
}
公共字符串postWithFiles(字符串URL,多部分M)抛出IOException异常{
ByteArrayOutputStream OUT =新ByteArrayOutputStream();
m.writeBodyTo(下)
;
Request.Body体= Request.Body.create(MediaType.parse(应用程序/ x-WWW的形式urlen codeD),
out.toByteArray());
请求REQ =新Request.Builder()网址(URL)。员额(体).build()。
返回client.newCall(REQ).execute()体()字符串()。
}
我的问题是:
- 如何设置的部分叫什么名字?在形式上,该文件应该被命名为文件1。
- 如何添加的形式与其他领域?
类多部分
从mimecraft封装整个HTTP身体,并能处理常规领域,像这样:
多部分M =新Multipart.Builder()
.TYPE(Multipart.Type.FORM)
.addPart(新Part.Builder()
。体(价值)
.contentDisposition(表格数据;名称= \non_file_field \)
。建立())
.addPart(新Part.Builder()
.contentType(文/ CSV)
。体(å文件)
.contentDisposition(表格数据;名称= \是,file_field \;文件名= \文件1 \)
。建立())
。建立();
看看的multipart / form-data编码让你如何需要构造部位的感觉。
一旦你有一个多部分
对象,所有剩下要做的就是指定正确的内容类型
报头和通过对主体的字节请求。
因为你似乎要与OkHttp API的2.0版,这是我没有经验与合作,这仅仅是猜测code:
//你可能需要更改的MediaType使用的Content-Type
//从多部分对象
Request.Body体= Request.Body.create(
MediaType.parse(m.getHeaders()获得(内容类型)),
out.toByteArray());
有关OkHttp 1.5.4,这里是一个剥离下来code我使用的是改编自的一个示例代码段:
OkHttpClient客户端=新OkHttpClient();
出的OutputStream = NULL;
尝试 {
网址URL =新的URL(http://www.example.com);
HttpURLConnection的连接= client.open(URL);
对于(Map.Entry的<字符串,字符串>进入:multipart.getHeaders()的entrySet()){
connection.addRequestProperty(entry.getKey(),entry.getValue());
}
connection.setRequestMethod(POST);
//写请求。
OUT = connection.getOutputStream();
multipart.writeBodyTo(出);
out.close();
//读取响应。
如果(connection.getResponse code()!= HttpURLConnection.HTTP_OK){
抛出新的IOException异常(意外的HTTP响应:
+ connection.getResponse code()++ connection.getResponseMessage());
}
} 最后 {
// 清理。
尝试 {
如果(满分!= NULL)out.close();
}赶上(例外五){
}
}
I use okhttp to be my httpclient. I think it's a good api but the doc is not so detailed.
how to use it to make a http post request with file uploading?
public Multipart createMultiPart(File file){
Part part = (Part) new Part.Builder().contentType("").body(new File("1.png")).build();
//how to set part name?
Multipart m = new Multipart.Builder().addPart(part).build();
return m;
}
public String postWithFiles(String url,Multipart m) throws IOException{
ByteArrayOutputStream out = new ByteArrayOutputStream();
m.writeBodyTo(out)
;
Request.Body body = Request.Body.create(MediaType.parse("application/x-www-form-urlencoded"),
out.toByteArray());
Request req = new Request.Builder().url(url).post(body).build();
return client.newCall(req).execute().body().string();
}
my question is:
- how to set part name? in the form, the file should be named file1.
- how to add other fields in the form?
The class Multipart
from mimecraft encapsulates the whole HTTP body and can handle regular fields like so:
Multipart m = new Multipart.Builder()
.type(Multipart.Type.FORM)
.addPart(new Part.Builder()
.body("value")
.contentDisposition("form-data; name=\"non_file_field\"")
.build())
.addPart(new Part.Builder()
.contentType("text/csv")
.body(aFile)
.contentDisposition("form-data; name=\"file_field\"; filename=\"file1\"")
.build())
.build();
Take a look at examples of multipart/form-data encoding to get a sense of how you need to construct the parts.
Once you have a Multipart
object, all that's left to do is specify the right Content-Type
header and pass on the body bytes to the request.
Since you seem to be working with the v2.0 of the OkHttp API, which I don't have experience with, this is just guess code:
// You'll probably need to change the MediaType to use the Content-Type
// from the multipart object
Request.Body body = Request.Body.create(
MediaType.parse(m.getHeaders().get("Content-Type")),
out.toByteArray());
For OkHttp 1.5.4, here is a stripped down code I'm using which is adapted from a sample snippet:
OkHttpClient client = new OkHttpClient();
OutputStream out = null;
try {
URL url = new URL("http://www.example.com");
HttpURLConnection connection = client.open(url);
for (Map.Entry<String, String> entry : multipart.getHeaders().entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
connection.setRequestMethod("POST");
// Write the request.
out = connection.getOutputStream();
multipart.writeBodyTo(out);
out.close();
// Read the response.
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Unexpected HTTP response: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
}
} finally {
// Clean up.
try {
if (out != null) out.close();
} catch (Exception e) {
}
}
这篇关于如何使用okhttp要上传的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!