首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用okhttp上传文件?

如何使用okhttp上传文件?
EN

Stack Overflow用户
提问于 2014-05-07 16:25:47
回答 7查看 79K关注 0票数 47

我使用okhttp作为我的httpclient。我认为这是一个很好的api,但文档并不那么详细。

如何使用它在上传文件时发出http post请求?

代码语言:javascript
复制
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();

}

我的问题是:

  1. 如何设置部件名称?在表单中,该文件应命名为file1。
  2. 如何在表单中添加其他字段?
EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2014-05-21 21:21:10

注意:此答案适用于okhttp 1.x/2.x。有关3.x,请参见this other answer

来自mimecraft的类Multipart封装了整个HTTP主体,并且可以处理常规字段,如下所示:

代码语言:javascript
复制
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();

看一看examples of multipart/form-data encoding,以了解您需要如何构造这些部分。

一旦拥有了Multipart对象,剩下的工作就是指定正确的Content-Type头并将主体字节传递给请求。

由于您似乎正在使用OkHttp应用程序接口的v2.0,而我没有使用经验,因此这只是一段猜测代码:

代码语言:javascript
复制
// 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());

对于OkHttp 1.5.4,以下是我正在使用的、改编自a sample snippet的精简代码

代码语言:javascript
复制
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) {
    }
}
票数 22
EN

Stack Overflow用户

发布于 2015-05-28 14:11:53

这是一个使用okhttp上传文件和一些任意字段的基本函数(它从字面上模拟了一个常规的HTML表单提交)

更改mime类型以匹配您的文件(这里我假设为.csv),或者如果您要上传不同类型的文件,则将其设置为函数的参数

代码语言:javascript
复制
  public static Boolean uploadFile(String serverURL, File file) {
    try {

        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse("text/csv"), file))
                .addFormDataPart("some-field", "some-value")
                .build();

        Request request = new Request.Builder()
                .url(serverURL)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(final Call call, final IOException e) {
                // Handle the error
            }

            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                if (!response.isSuccessful()) {
                    // Handle the error
                }
                // Upload successful
            }
        });

        return true;
    } catch (Exception ex) {
        // Handle the error
    }
    return false;
}

注意:因为它是异步调用,所以boolean返回类型不是,而是只表示请求已提交到okhttp队列。

票数 51
EN

Stack Overflow用户

发布于 2016-04-28 04:06:44

这是一个适用于OkHttp 3.2.0的答案:

代码语言:javascript
复制
public void upload(String url, File file) throws IOException {
    OkHttpClient client = new OkHttpClient();
    RequestBody formBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("file", file.getName(),
            RequestBody.create(MediaType.parse("text/plain"), file))
        .addFormDataPart("other_field", "other_field_value")
        .build();
    Request request = new Request.Builder().url(url).post(formBody).build();
    Response response = client.newCall(request).execute();
}
票数 47
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23512547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档