用okhttp上传文件

我正在完成这个使用okhttp与web服务进行通信的项目。

对于定期的GET和POST,一切都很顺利,但我无法正确上传文件。

okhttp文档是非常缺乏这些主题,我发现这里或任何地方的一切似乎并没有在我的情况下工作。

这应该是简单的:我必须发送文件和一些string值。 但是我不知道该怎么做。

继我发现的一些样品之后,我首先尝试了这个:

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(); 

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

所以我尝试了这个从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(); 

同样的结果。

不知道还有什么要尝试或调查什么。

请求是用这个代码完成的:

 // 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(); 

但我很确定,问题是如何build立请求主体。

我究竟做错了什么?

编辑:上面的“getFile()”顺便返回一个File对象。 其余的参数都是string和整数。

我在最初的post后find了自己的问题的答案。

我会把它留在这里,因为它可以对其他人有用,因为有这么几个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(); 

没有理由像在食谱中使用“addPart”和“Headers.of”等,addFormDataPart是诀窍。

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

我只是改变了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; } 

OKHTTP 3+使用这个AsyncTask

SignupWithImageTask

  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(); } } }