无法将照片上传到服务器android改造2

时间:2019-12-11 14:35:12

标签: java android retrofit retrofit2

我正在尝试将照片上传到后端开发人员提供此json文件的服务器:

{"name":"update-profilePatient",
 "request":{ 
  "method":"POST",
   "header":[],
   "body":{ 
   "mode":"formdata",
   "formdata":[ 
    {"key":"user_id","value":"","description":"type user id = 8 patient","type":"text"},
    { "key":"image","type":"file","src":[]},
    { "key":"firstname","value":"","type":"text"},
    {"key":"lastname",value":"","type":"text"}]}

如果使用此方法,它将以字符串形式上传数据而没有照片:

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
Retrofit re = new Retrofit.Builder().baseUrl(ApiUrl).addConverterFactory(GsonConverterFactory.create()).client(httpClient.build()).build();
MyApi api = re.create(MyApi.class);
Map<String, String> sMap = new HashMap<>();
sMap.put("user_id", info.getId() + "");
sMap.put("firstname", info.getFirst_name());
sMap.put("lastname", info.getLast_name());
sMap.put("birthday", info.getBirthday());
sMap.put("phone", info.getPhone());
sMap.put("gender", info.getGender());
sMap.put("city_id", info.getCity_id());
sMap.put("area_id", "1");
sMap.put("Address", info.getAddress());
sMap.put("latitude", info.getLatitude() + "");
sMap.put("longitude", info.getLongitude() + "");
sMap.put("image", photo(info.getPhoto().replace(photoLink, "")));
sMap.put("other", "other");
Call<ResponseBody> request = api.updatePatientsWithePhoto(sMap);
request.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(@NotNull Call<ResponseBody> call, @NotNull Response<ResponseBody> response) {Log.e("EditPaWithPhoto", "onResponse: " + response);
}
@Override
public void onFailure(@NotNull Call<ResponseBody> call, @NotNull Throwable t) {
Log.e("EditPaWithPhoto", "Throwable: " + t.getMessage());
}});

// intrface Code
@POST("update-profilePatient")
@Headers({"Content-Type: application/json;charset=UTF-8"})
Call<ResponseBody> updatePatientsWithePhoto
        (
                @Body Map<String,String> json
        );

但是,如果我使用此方法上传数据,则会失败:

@Multipart
@POST("update-profilePatient")
@Headers({"Content-Type: application/json;charset=UTF-8"})
Call<ResponseBody> updatePatientsWithePhoto
(@Part("user_id") RequestBody user_id,
 @Part("firstname") RequestBody firstname,
 @Part("lastname") RequestBody lastname,
 @Part("birthday") RequestBody birthday,
 @Part("phone") RequestBody phone,
 @Part("gender") RequestBody gender,
 @Part("city_id") RequestBody city_id,
 @Part("area_id") RequestBody area_id,
 @Part("Address") RequestBody Address,
 @Part("latitude") RequestBody latitude,
 @Part("longitude") RequestBody longitude,
 @Part("other") RequestBody other,@Part MultipartBody.Part image);

File photoFile = new File(info.getPhoto().replace(photoLink, ""));
RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), photoFile);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("image", photoName,fileBody );
Call<ResponseBody> request = api.updatePatientsWithePhoto(
toRequestBody(info.getId()+""),
toRequestBody(info.getFirst_name()),
toRequestBody(info.getLast_name()),
toRequestBody(info.getBirthday()),
toRequestBody(info.getPhone()),
toRequestBody(info.getGender()),
toRequestBody(info.getCity_id()),
toRequestBody("1"),
toRequestBody(info.getAddress()),
toRequestBody(info.getLatitude()+""),
toRequestBody(info.getLongitude()+""),
toRequestBody("1"),
filePart);

然后我得到此日志:

  

D / OkHttp:--e64d0c37-dddf-4a7e-a​​5ed-d6104271a7c4--       D / OkHttp:-> END POST(2734字节的正文)       D / OkHttp:<-401未经授权的MyUrl / api / update-profilePatient(1325毫秒)       D / OkHttp:Date:Sun,08 Dec 2019 09:28:21 GMT       D / OkHttp:服务器:Apache       D / OkHttp:缓存控制:无缓存,私有       D / OkHttp:X-RateLimit-Limit:60       D / OkHttp:X-RateLimit-剩余:55       D / OkHttp:升级:h2,h2c       D / OkHttp:连接:升级,保持活动       D / OkHttp:变化:接受编码       D / OkHttp:推荐人政策:降级时没有推荐人       D / OkHttp:保持活动:超时= 5,最大= 75       D / OkHttp:内容类型:application / json       D / OkHttp:{“状态”:false,“错误”:{“ user_id”:[“用户ID字段为必填。”],“名字”:[“       名字字段为必填。“],”姓氏“:[”姓氏为必填。“],”生日“:[”       生日字段为必填。“],”电话“:[”电话字段为必填。“],”性别“:[”性别字段       为必填。“],” city_id“:[”必填城市ID。“],” area_id“:[”区域ID为       必填。“],”其他“:[”必填其他字段。“],”地址“:[”必填地址字段。“]}}       D / OkHttp:<-END HTTP(474字节的正文)

邮递员 enter image description here

2 个答案:

答案 0 :(得分:0)

您应该使用multipart/form-data而不是application/json;charset=UTF-8

因为如果您拦截基础的OkHttp客户端并将内容类型更改为application / json,则服务器可能会在反序列化过程中遇到问题。

有关更多信息,请参见Upload Files With Retrofit 2

答案 1 :(得分:0)

这可以解决问题

界面代码

@Multipart
@POST("update-profilePatient")
Call<ResponseBody> updatePatientsWithePhoto
(@Part("user_id") RequestBody user_id,
 @Part("firstname") RequestBody firstname,
 @Part("lastname") RequestBody lastname,
 @Part("birthday") RequestBody birthday,
 @Part("phone") RequestBody phone,
 @Part("gender") RequestBody gender,
 @Part("city_id") RequestBody city_id,
 @Part("area_id") RequestBody area_id,
 @Part("Address") RequestBody Address,
 @Part("latitude") RequestBody latitude,
 @Part("longitude") RequestBody longitude,
 @Part("other") RequestBody other,@Part MultipartBody.Part image);

//这样的呼叫

Call<ResponseBody> request = api.updatePatientsWithePhoto(
                toRequestBody(info.getId()+""),
                toRequestBody(info.getFirst_name()),
                toRequestBody(info.getLast_name()),
                toRequestBody(info.getBirthday()),
                toRequestBody(info.getPhone()),
                toRequestBody(info.getGender()),
                toRequestBody(info.getCity_id()),
                toRequestBody("1"),
                toRequestBody(info.getAddress()),
                toRequestBody(info.getLatitude()+""),
                toRequestBody(info.getLongitude()+""),
                toRequestBody("1"),
                filePart);
        //Call<ResponseBody> request = api.updatePatientsWithePhoto(sMap,fileBody);
        request.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NotNull Call<ResponseBody> call
                    , @NotNull Response<ResponseBody> response) {
                Log.e("EditPaWithPhoto", "onResponse: " + response);
            }
            //
            @Override
            public void onFailure(@NotNull Call<ResponseBody> call, @NotNull Throwable t) {
                Log.e("EditPaWithPhoto", "Throwable: " + t.getMessage());

            }
        });