개조를 사용하여이 Postdata와 imagefile을 동시에 보내고 싶습니다.개조를 사용하여 이미지와 텍스트를 동시에 보내는 방법
과 PostData 및 포인트
public class PostData implements Serializable {
@Expose
private String text;
@Expose
private Point point;
}
public class Point implements Serializable {
@Expose
private double longitude;
@Expose
private double latitude;
}
PostApiService는
public interface PostApiService {
@Multipart
@POST("posts/")
Call<ResponseBody> uploadFile (@Part MultipartBody.Part part, @Body PostData postData);
}
나는이 코드에서 이미지 URI를 얻고, 나는 그것을 사용합니다. 그것은 returnUri로 사용됩니다. 이것을 고려해보십시오.
CODE :
view.findViewById(R.id.btn_post).setOnClickListener(new View.OnClickListener() {
@Override
public void PostImageAndData(View view) {
Bitmap bitmap = null;
try {
bitmap = getBitmapFromUri(returnUri); #this method is to make Bitmap from Uri
} catch (IOException e) {
e.printStackTrace();
}
File imageFile = null;
try {
imageFile = createFileFromBitmap(bitmap); #this method is to make File from Bitmap
} catch (IOException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Constants.HTTP.BASE_URL)
.build();
PostApiService postApiService = retrofit.create(PostApiService.class);
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", makeImageFileName(), requestFile); #this method(makeimageFileName()) is for custom filename
Point mpoint = new Point(13, 15);
PostData postData = new PostData("hello", mpoint);
Call<ResponseBody> call = postApiService.uploadFile(body, postData);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(getContext(), "success?", Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
});
내가 PostApiService에 @Body PostData postData
를 사용하는 경우, 오류가 java.lang.IllegalArgumentException: @Body parameters cannot be used with form or multi-part encoding. (parameter #2)
하고 난 PostApiService에 @Part PostData postData
를 사용하는 경우, 오류는 어떻게해야합니까, 그래서 java.lang.IllegalArgumentException: @Part annotation must supply a name or use MultipartBody.Part parameter type. (parameter #2)
입니다 ?
제발, 도와 주시겠습니까?
retrofit2는 내가 예측 한 것보다 훨씬 더 사용하기가 어렵습니다. 고맙습니다. Saveen –
예, 저도 어제까지 : 걱정 마세요. – Saveen