【问题标题】:Retrofit2 upload onFailureRetrofit2 上传失败
【发布时间】:2017-05-06 09:47:24
【问题描述】:

上传错误:使用 JsonReader.setLenient(true) 在第 15 行第 1 列路径 $enter code here 接受格式错误的 JSON

我想上传一些图片,但错误:使用 JsonReader.setLenient(true) 在第 15 行第 1 列路径接受格式错误的 JSON。 我多次改写 URl 和改写 JavaBean,同时出错。

这个Retrofit2界面:

public interface ImageUpload {

@Multipart
@POST("/xxzx/a/tpsb/uploadPicture")
Call<UploadResult> uploadMultipleFiles(
        @PartMap Map<String, RequestBody> files
        );

初始化改造2:

public class ServiceGenerator {

private static final String API_BASE_URL= "http://114.115.139.232:8080/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

private static Retrofit.Builder builder =
        new Retrofit.Builder()
        .baseUrl(API_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create());

public static <S> S createService(Class<S> serviceClass){
    Retrofit retrofit = builder.client(httpClient.build()).build();
    return retrofit.create(serviceClass);
}

调用 Retrofit2:

    private void uploadFiles() {
    
        if(imagesList.size()==0){
            Toast.makeText(MainActivity.this, "nothing", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, RequestBody>files = new HashMap<>();
        final ImageUpload service = ServiceGenerator.createService(ImageUpload.class);
        for (int i = 0;i<imagesList.size();i++){
            File file = new File(imagesList.get(i).path);
            files.put("file" + i + "\"; filename=\"" + file.getName(),
                    RequestBody.create(MediaType.parse(imagesList.get(i).mimeType), file));
        }
        Call<UploadResult> call = service.uploadMultipleFiles(files);
        call.enqueue(new Callback<UploadResult>() {
            @Override
            public void onResponse(Call<UploadResult> call, Response<UploadResult> response) {
                if (response.isSuccessful()){
                    Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
                }
            }

        @Override
        public void onFailure(Call<UploadResult>call, Throwable t) {
            Log.i("wxl", "onFailure=" + t.getMessage());
            Toast.makeText(MainActivity.this,"error", Toast.LENGTH_SHORT).show();
        }
    });
}

他用过邮递员的帖子:

{
"failureList": [],
"successNum": 1,
"failureNum": 0
}

javabean:

public class UploadResult<T> { 
    public int successNum;
    public int failureNum;
    public ArrayList<String> failureList;
    }

【问题讨论】:

标签: java android retrofit2


【解决方案1】:

这使用 Postman 发布。但是我不确定你是如何通过邮递员上传图片的,我可能不知道。 但是您需要记录实际出现在您的 android 日志中的数据

使用 Http Interceptor 记录日志:

  HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

这是因为您可能从改造客户端的请求中获取了不同的数据,这可能无法序列化您的数据。

休息一切似乎都很好。

注意:不要在 api 界面中使用“/”,因为您已经添加到基本 url 的末尾

【讨论】:

    【解决方案2】:

    在你的 init Retrofit 方法上试试这个:

    private static Retrofit.Builder builder =
    
       Gson gson = new GsonBuilder()
       setLenient()
       .create();
    
    
    
        new Retrofit.Builder()
        .baseUrl(API_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gson));
    

    【讨论】:

      【解决方案3】:

      依赖::

        implementation 'io.reactivex.rxjava2:rxjava:2.2.3'
          implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
          implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
          implementation 'com.google.code.gson:gson:2.8.5'
      

      api客户端::

      import retrofit2.Retrofit;
      import retrofit2.converter.gson.GsonConverterFactory;
      
      
      public class ApiClient {
      
          public static final String BASE_URL = "https://graph.facebook.com/";
          private static Retrofit retrofit = null;
      
      
          public static Retrofit getClient() {
              if (retrofit==null) {
                  retrofit = new Retrofit.Builder()
                          .baseUrl(BASE_URL)
                          .addConverterFactory(GsonConverterFactory.create())
                          .build();
              }
              return retrofit;
          }
      }
      

      请求接口:

      String ENDPOINT_LOGIN = "era/user/login";
          //params
          String PARAM_USER_USERNAME = "username";
          String PARAM_USER_PASSWORD = "password";
      
      
          //sign_up_coach_data
      String ENDPOINT_ALL_SIGNOUT = "user/fcm";
          String ENDPOINT_SIGN_UP = "user/create";
          String ENDPOINT_OPT = "user/verify";
         String ENDPOINT_ALL_CITIES = "cities/get";
      
      
        @FormUrlEncoded
          @POST(ENDPOINT_ALL_SIGNOUT)
          Call<BaseResponse> getSignOut(
                  @Header("Authorization") String token,
                  @Field(PARAM_USER_FCM) String fcm
          );
      
          @GET(ENDPOINT_ALL_CITIES)
          Call<GetAllCitiesResponse> ();
      

      网络服务助手::

      public static Call<BaseResponse> getSignOut(String token) {
      
      
              return getRetrofit().create(RequestAPIs.class)
                      .getSignOut(token, ""
                      );
      
          }
      
      
       public static Call<GetAllCitiesResponse> getAllCities() {
      
              return getRetrofit().create(RequestAPIs.class)
                      .getAllCities();
          }
      

      活动API调用::

       private void getSignOut() {
              Callback<BaseResponse> categoryCallback = new Callback<BaseResponse>() {
                  @Override
                  public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                      stopProgress();
                      Log.d("tag", "response :: " + response.isSuccessful());
                      if (response.isSuccessful()) {
                          if (response.body().isStatus()) {
                              Log.d("tag", "response :: " + response.body().getData());
                              Helper.clearPreferences(getApplicationContext());
                              editor.clear();
                              Intent intent = new Intent(MapsActivity.this, StartActivity.class);
                              intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                              intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                              startActivity(intent);
                              MapsActivity.this.finish();
      
                          } else {
                              PrettyDialogMessage(String.valueOf(response.body().getErrors()));
                          }
                      } else {
                          PrettyDialogMessage(getString(R.string.ws_failure));
                      }
                  }
      
                  @Override
                  public void onFailure(Call<BaseResponse> call, Throwable t) {
                      stopProgress();
                      Log.d("tag", "response :: " + t.toString());
                      //toast(getString(R.string.ws_failure));
                  }
              };
              startProgress(false);
      
              WebServiceHelper.getSignOut(Helper.getStringValue(getApplicationContext(), KEY_BARER)).enqueue(categoryCallback);
      
          }
      
      
       private void getAllCities() {
      
      
              Callback<GetAllCitiesResponse> getAllCitiesResponseCallback = new Callback<GetAllCitiesResponse>() {
                  @Override
                  public void onResponse(Call<GetAllCitiesResponse> call, Response<GetAllCitiesResponse> response) {
                      stopProgress();
                      Log.d("tag", "response :: " + response.isSuccessful());
                      if (response.isSuccessful()) {
                          if (response.body().isStatus()) {
                              Log.d("tag :: ", "response :  " + response.body().getData());
      
                              for (int i = 0; i < response.body().getData().get(i).getCityBoundry().getCoordinates().size(); i++) {
                                  UserLatLang userLatLang = new UserLatLang(response.body().getData().get(i).getCityBoundry().getCoordinates().get(i).getLat(), response.body().getData().get(i).getCityBoundry().getCoordinates().get(i).getLng());
                                  polygonData.add(new LatLng(userLatLang.getLattitude(), userLatLang.getLongitude()));
                              }
      
                              if (isPointInPolygon(new LatLng(userLattitude, userLongitude), polygonData)) {
                                  if (polygonData != null)
                                      polygonData.clear();
                                  progressDialog.dismiss();
                                  appPrefrence.SetUserCity(prefCity);
                                  Intent intent = new Intent(LoginActivity.this, MapsActivity.class);
                                  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                  startActivity(intent);
                                  return;
                              } else {
                                  if (polygonData != null)
                                      polygonData.clear();
                              }
                          }
                          progressDialog.dismiss();
                          appPrefrence.SetUserCity("Jacksonville Beaches");
                          Intent intent = new Intent(LoginActivity.this, MapsActivity.class);
                          intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                          startActivity(intent);
      
                      } else {
                          PrettyDialogMessage(String.valueOf(response.body().getErrors()));
                      }
                  }
      
                  @Override
                  public void onFailure(Call<GetAllCitiesResponse> call, Throwable t) {
                      stopProgress();
                      Log.d("tag", "response :: " + t.toString());
                      //toast(getString(R.string.ws_failure));
                  }
              };
              startProgress(false);
      
              WebServiceHelper.getAllCities().enqueue(getAllCitiesResponseCallback);
      
      
          }
      

      【讨论】:

        猜你喜欢
        • 2016-07-29
        • 1970-01-01
        • 2012-12-20
        • 2014-01-19
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多