java 使用okhttp上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30339303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:56:16  来源:igfitidea点击:

File upload with okhttp

javaandroidokhttp

提问by diogo.abdalla

Im finishing this project which is using okhttp for communication with a webservice.

我正在完成这个使用 okhttp 与网络服务通信的项目。

All is going fine for regular GETs and POSTs, but I'm not being able to properly upload a file.

对于常规 GET 和 POST 一切正常,但我无法正确上传文件。

The okhttp docs are very lacking on these subjects and everything I found here or anywhere don't seem to work in my case.

okhttp 文档在这些主题上非常缺乏,我在这里或任何地方找到的所有内容似乎都不适用于我的情况。

It's supposed to be simple: I have to send both the file and some string values. But I can't figured out how to do it.

这应该很简单:我必须同时发送文件和一些字符串值。但我不知道该怎么做。

Following the some samples I found, I first tried this:

按照我发现的一些样本,我首先尝试了这个:

RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
    .addFormDataPart("group", getGroup())
    .addFormDataPart("type", getType())
    .addFormDataPart("entity", Integer.toString(getEntity()))
    .addFormDataPart("reference", Integer.toString(getReference()))
    .addPart(Headers.of("Content-Disposition", "form-data; name=\"task_file\""), RequestBody.create(MediaType.parse("image/png"), getFile()))
    .build();

It gives me a "400 bad request" error.

它给了我一个“400 个错误的请求”错误。

So I tried this from the okhttp recipes:

所以我从 okhttp 食谱中尝试了这个:

RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
    .addPart(Headers.of("Content-Disposition", "form-data; name=\"group\""), RequestBody.create(null, getGroup()))
    .addPart(Headers.of("Content-Disposition", "form-data; name=\"type\""), RequestBody.create(null, getType()))
    .addPart(Headers.of("Content-Disposition", "form-data; name=\"entity\""), RequestBody.create(null, Integer.toString(getEntity())))
    .addPart(Headers.of("Content-Disposition", "form-data; name=\"reference\""), RequestBody.create(null, Integer.toString(getReference())))
    .addPart(Headers.of("Content-Disposition", "form-data; name=\"task_file\""), RequestBody.create(MediaType.parse("image/png"), getFile()))
    .build();

Same result.

结果一样。

Don't know what else to try or what look into to debug this.

不知道还有什么要尝试的,也不知道要调试什么。

The request is done with this code:

使用以下代码完成请求:

// adds the required authentication token
Request request = new Request.Builder().url(getURL()).addHeader("X-Auth-Token", getUser().getToken().toString()).post(requestBody).build();
Response response = client.newCall(request).execute();

But Im pretty sure that the problem is how Im building the request body.

但我很确定问题在于我如何构建请求正文。

What am I doing wrong?

我究竟做错了什么?

EDIT: "getFile()" above returns the a File object, by the way. The rest of the parameters are all strings and ints.

编辑:顺便说一下,上面的“getFile()”返回了一个 File 对象。其余的参数都是字符串和整数。

回答by diogo.abdalla

I found answer to my own question a bit after initial post.

在最初的帖子后,我找到了我自己的问题的答案。

I′ll leave it here, because it can be useful to others, given that there is such a few okhttp upload examples around:

我就留在这里,因为它可以对其他人有用,因为周围有这么几个okhttp上传示例:

RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
        .addFormDataPart("group", getGroup())
        .addFormDataPart("type", getType())
        .addFormDataPart("entity", Integer.toString(getEntity()))
        .addFormDataPart("reference", Integer.toString(getReference()))
        .addFormDataPart("task_file", "file.png", RequestBody.create(MediaType.parse("image/png"), getFile()))
                                                .build();

There is no reason to use "addPart" with "Headers.of" etc like in the recipes, addFormDataPart does the trick.

没有理由在食谱中使用“addPart”和“Headers.of”等,addFormDataPart 可以解决问题。

And for the file field itself, it takes 3 arguments: name, filename and then the file body. That's it.

对于文件字段本身,它需要 3 个参数:名称、文件名和文件正文。而已。

回答by Pratik Butani

I just changed addFormDataPartinstead addPartand Finally solved My Problem Using following code:

我只是改变了 addFormDataPart,而不是addPart和最后解决我的问题使用下面的代码:

  /**
     * Upload Image
     *
     * @param memberId
     * @param sourceImageFile
     * @return
     */
    public static JSONObject uploadImage(String memberId, String sourceImageFile) {

        try {
            File sourceFile = new File(sourceImageFile);

            Log.d(TAG, "File...::::" + sourceFile + " : " + sourceFile.exists());

            final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

            RequestBody requestBody = new MultipartBuilder()
                    .type(MultipartBuilder.FORM)
                    .addFormDataPart("member_id", memberId)
                    .addFormDataPart("file", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
                    .build();

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

            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            return new JSONObject(response.body().string());

        } catch (UnknownHostException | UnsupportedEncodingException e) {
            Log.e(TAG, "Error: " + e.getLocalizedMessage());
        } catch (Exception e) {
            Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
        }
        return null;
    }

回答by Arpit Patel

in OKHTTP 3+use this AsyncTask

OKHTTP 3+ 中使用这个AsyncTask

SignupWithImageTask

使用ImageTask注册

  public class SignupWithImageTask extends AsyncTask<String, Integer, String> {

        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(SignupActivity.this);
            progressDialog.setMessage("Please Wait....");
            progressDialog.show();
        }

        @Override
        protected String doInBackground(String... str) {

            String res = null;
            try {
//                String ImagePath = str[0];
                String name = str[0], email = str[1], dob = str[2], IMEI = str[3], phone = str[4], ImagePath = str[5];

                File sourceFile = new File(ImagePath);

                Log.d("TAG", "File...::::" + sourceFile + " : " + sourceFile.exists());

                final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");

                String filename = ImagePath.substring(ImagePath.lastIndexOf("/") + 1);

                /**
                 * OKHTTP2
                 */
//            RequestBody requestBody = new MultipartBuilder()
//                    .type(MultipartBuilder.FORM)
//                    .addFormDataPart("member_id", memberId)
//                    .addFormDataPart("file", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
//                    .build();

                /**
                 * OKHTTP3
                 */
                RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("image", filename, RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
                        .addFormDataPart("result", "my_image")
                        .addFormDataPart("name", name)
                        .addFormDataPart("email", email)
                        .addFormDataPart("dob", dob)
                        .addFormDataPart("IMEI", IMEI)
                        .addFormDataPart("phone", phone)
                        .build();

                Request request = new Request.Builder()
                        .url(BASE_URL + "signup")
                        .post(requestBody)
                        .build();

                OkHttpClient client = new OkHttpClient();
                okhttp3.Response response = client.newCall(request).execute();
                res = response.body().string();
                Log.e("TAG", "Response : " + res);
                return res;

            } catch (UnknownHostException | UnsupportedEncodingException e) {
                Log.e("TAG", "Error: " + e.getLocalizedMessage());
            } catch (Exception e) {
                Log.e("TAG", "Other Error: " + e.getLocalizedMessage());
            }


            return res;

        }

        @Override
        protected void onPostExecute(String response) {
            super.onPostExecute(response);
            if (progressDialog != null)
                progressDialog.dismiss();

            if (response != null) {
                try {

                    JSONObject jsonObject = new JSONObject(response);


                    if (jsonObject.getString("message").equals("success")) {

                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");

                        SharedPreferences settings = getSharedPreferences("preference", 0); // 0 - for private mode
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString("name", jsonObject1.getString("name"));
                        editor.putString("userid", jsonObject1.getString("id"));
                        editor.putBoolean("hasLoggedIn", true);
                        editor.apply();

                        new UploadContactTask().execute();

                        startActivity(new Intent(SignupActivity.this, MainActivity.class));
                    } else {
                        Toast.makeText(SignupActivity.this, "" + jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(SignupActivity.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
            }

        }
    }

回答by Oyewo Remi

Here is how to upload file using okhttp3.

下面是如何使用okhttp3上传文件。

      try {

          UpdateInformation("yourEmailAddress", filePath, sourceFile);

          } catch (IOException e) {
                        e.printStackTrace();
         }

    private void UploadInformation(String email, final String _filePath, final File file) throws IOException {


        runOnUiThread(new Runnable() {
            @Override
            public void run() {


            //show progress bar here

            }
        });


        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();





        String mime = getMimeType(_filePath);


        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse(mime), file))
                .addFormDataPart("email", email)
                .build();





        okhttp3.Request request = new okhttp3.Request.Builder()
                .url("yourEndPointURL")
                .post(body)
                .addHeader("authorization", "yourEndPointToken")
                .addHeader("content-type", "application/json")
                .build();



        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                call.cancel();


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    //hide progress bar here

                    }
                });

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {


                try {

                    final String myResponse = response.body().string();


                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                    //hide progress bar here

                    //Cont from here
                    //Handle yourEndPoint Response.



                        }
                    });


                } catch (Exception e) {
                    e.printStackTrace();
                }


            }



        });
    }


private String getMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null)
        {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

Hope this helps.

希望这可以帮助。