2015-05-20 15 views
8

Im finendo questo progetto che utilizza okhttp per la comunicazione con un webservice.Caricamento file con okhttp

Tutto sta andando bene per regolari GET e POST, ma non riesco a caricare correttamente un file.

I documenti di okhttp sono molto carenti su questi argomenti e tutto ciò che ho trovato qui o altrove non sembra funzionare nel mio caso.

Si suppone che sia semplice: devo inviare sia il file che alcuni valori di stringa. Ma non riesco a capire come farlo.

Dopo i campioni che ho trovato, ho provato questo:

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

Mi dà un errore "400 Bad Request".

Così ho provato questo dalle ricette 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(); 

stesso risultato.

Non so che altro provare o che cosa cercare per eseguire il debug di questo.

La richiesta è fatto con questo codice:

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

Ma Im abbastanza sicuro che il problema è come Im la costruzione del corpo della richiesta.

Cosa sto sbagliando?

MODIFICA: "getFile()" sopra restituisce l'oggetto File, a proposito. Il resto dei parametri sono tutte stringhe e int.

risposta

20

Ho trovato la risposta alla mia domanda un po 'dopo il post iniziale.

I'll lasciarlo qui, perché può essere utile per gli altri, visto che non v'è una tale alcuni esempi di upload okhttp giro:

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

non v'è alcun motivo di usare "AddPart" con "intestazioni .di "ecc. come nelle ricette, addFormDataPart fa il trucco.

E per il campo stesso, sono necessari 3 argomenti: nome, nome file e quindi il corpo del file. Questo è tutto.

+0

grazie diogo.abdalla mi ha svegliato per me .. –

+0

Ho affrontato lo stesso problema ... chiedendomi perché le Ricette suggerissero di usare "addPart" con "Headers.of". – Jsm

+0

Cosa sta facendo la funzione getFile()? È dato per il percorso dell'immagine? –

6

Ho appena cambiato addFormDataPart invece addPart e infine risolto il mio problema Utilizzando seguente codice:

/** 
    * 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

puoi dare il codice lato server se stai usando php ?? – Rookie

+0

cos'è MultipartBuilder. Shubhank ha detto che è la parte di okHttp ma quando la prendo nel mio progetto non si risolve e mi dà errore – Jumong

1

in OKHTTP 3+ uso questo 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(); 
      } 

     } 
    }