2015-05-20 27 views
8

Kończę ten projekt, który używa okhttp do komunikacji z serwisem internetowym.Przesyłanie plików z okhttp

Wszystko jest w porządku dla zwykłych GET i POST, ale nie jestem w stanie prawidłowo załadować pliku.

Dokumenty okhttp są bardzo brakuje na te tematy i wszystko, co znalazłem tutaj lub gdziekolwiek nie wydaje się działać w moim przypadku.

To powinno być proste: muszę wysłać zarówno plik, jak i niektóre wartości ciągu. Ale nie mogę wymyślić, jak to zrobić.

następstwie niektórych próbkach znalazłem, po raz pierwszy próbowałem:

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

Daje mi "400 Bad request" błąd.

Więc próbowałem to z okhttp Przepisy:

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

sam rezultat.

Nie wiem, co jeszcze wypróbować lub na co zaglądnąć, aby to usunąć.

Żądanie odbywa się za pomocą tego kodu:

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

Ale jestem pewien, że problemem jest to, jak Im budowy ciała żądania.

Co robię źle?

EDYCJA: "getFile()" powyżej zwraca obiekt File, przy okazji. Pozostałe parametry są ciągami i intami.

Odpowiedz

20

Znalazłem odpowiedź na moje własne pytanie nieco po pierwszym poście.

I'll zostawić go tutaj, bo może to być przydatne dla innych, biorąc pod uwagę, że nie jest tak kilka przykładów okhttp wysyłania wokół:

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

Nie ma powodu, aby użyć „addPart” z „nagłówkami z "itp. jak w przepisach, addFormDataPart robi lewę.

A dla samego pola pliku zajmuje 3 argumenty: nazwę, nazwę pliku, a następnie treść pliku. to jest to!

+0

dzięki diogo.abdalla obudził się dla mnie .. –

+0

Zmierzyłem się z tym samym problemem ... zastanawiając się, dlaczego przepisy sugerują użycie "addPart" z "Headers.of". – Jsm

+0

Co robi funkcja getFile()? Czy jest podana dla ścieżki obrazu? –

6

Właśnie zmienił addFormDataPart zamiast addPart i wreszcie rozwiązać mój problem Korzystanie poniższy kod:

/** 
    * 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; 
    } 
+0

Czy możesz podać kod po stronie serwera, jeśli używasz php ?? – Rookie

+0

czym jest MultipartBuilder. shubhank powiedział, że jest to część okHttp, ale kiedy biorę to w moim projekcie, to nie rozwiązuje i daje mi błąd – Jumong

1

w OKHTTP 3+ stosowania tego 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(); 
      } 

     } 
    }