Retrofit2上传失败

时间:2017-05-06 09:47:24

标签: java android retrofit2

上传错误:使用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
        );

Init Retrofit2:

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

你曾经使用Postman帖子:

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

的JavaBean:

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

3 个答案:

答案 0 :(得分:1)

这使用Postman帖子。但是,我不知道你是如何通过邮政人员上传图像可能是我不知道。 但是您需要记录实际出现在Android日志中的数据

使用Http Interceptor记录日志:

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

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

休息一切似乎没问题。

注意:不要在你的api界面中使用'/',因为你已经添加到基本网址的结尾

答案 1 :(得分:0)

尝试使用您的init改造方法:

private static Retrofit.Builder builder =

   Gson gson = new GsonBuilder()
   setLenient()
   .create();



    new Retrofit.Builder()
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create(gson));

答案 2 :(得分:0)

依赖项::

  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;
    }
}

请求api:

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

webservice助手::

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


    }