2016-03-30 8 views
3

ファイル:目標は、いくつかの文字列/整数フィールドを持つオブジェクトJSONを送信し、私は<strong>Retrofit2</strong>でサーバーにPOSTリクエストを送信するために使用Retrofit2

@POST("goals") 
    Call<Void> postGoal(@Body Goal goal); 

あった場所。

ここに写真ファイルを追加する必要があります。 私はマルチパート使用するスイッチする必要が知っている:

@Multipart 
    @POST("goals") 
    Call<Void> postGoal(
      @Part("picture") RequestBody picture 
      ); 

//... 
//Instantaining picture 
RequestBody.create(MediaType.parse("image/*"), path) 

をしかし、どのように私は、以前のフィールドを追加することが出来るのですか?特に、Goalオブジェクト全体をフィールドに分割することなく追加する方法はありますか? JSONを送信するためretrofit-2-how-to-upload-files-to-server

+1

解決方法を見つけましたか? – Amir

答えて

0

あなたはより詳細な情報を見つけることができます。この

@Multipart 
    @POST("goals") 
    Call<Void> postGoal(
      @Part("picture") RequestBody picture, 
      @Part("goal") RequestBody goal 
      ); 

    //... 
    //Instantaining picture 
    RequestBody.create(MediaType.parse("image/*"), path) 

ようにあなたの目標と@Partを追加することができます。

@Multipart 
@POST("goals") 
Call<JsonModel> postGoal(@Part MultipartBody.Part file, @Part("json") RequestBody json); 

ここで、jsonとして送信したいオブジェクトをGsonを使用してjsonに変換します。このような

String json = new Gson().toJson(new Goal()); 

    File file = new File(path); 
         RequestBody requestFile = 
           RequestBody.create(MediaType.parse("multipart/form-data"), file); 

         // MultipartBody.Part is used to send also the actual file name 
         MultipartBody.Part body = 
           MultipartBody.Part.createFormData("picture", file.getName(), requestFile); 

         // add another part within the multipart request 
         RequestBody jsonBody= 
           RequestBody.create(
             MediaType.parse("multipart/form-data"), json); 
         Retrofit retrofit = new Retrofit.Builder() 
           .baseUrl(url) 
           .addConverterFactory(GsonConverterFactory.create()) 
           .build(); 
         RestApi api = retrofit.create(RestApi.class); 
         Call<ResponseBody> call = api.upload(jsonBody, body); 
         call.enqueue(new Callback<ResponseBody>() { 
          @Override 
          public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 
           Log.d("onResponse: ", "success"); 
          } 

          @Override 
          public void onFailure(Call<ResponseBody> call, Throwable t) { 
           Log.d("onFailure: ", t.getLocalizedMessage()); 
          } 
         }); 
0

、あなたはこのような何かに従うことができますファイル:

関連する問題