尝试通过改型上载图像时,如何解析JSON文档未完全使用

时间:2019-06-20 12:05:26

标签: java android retrofit image-uploading

我写了一个电话,要求通过改造将图像上传到服务器。我想我已经按照这里的步骤进行了操作。

但是从这些步骤中我没有得到任何积极的结果。

我一直都在收到“ com.google.gson.JsonIOException:JSON文档没有被完全使用”的异常。

这是我要执行的步骤,

public void uploadBasicImage(String fileNamePath) {
        String[] split = fileNamePath.split("/");
        String filename = split[split.length-1];

        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File file = new File(path, filename +".jpg");
        try {
            path.mkdirs();
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("img", file.getName(), requestBody);

        if (ApiClient.getRefreshedToken(context) == null) {
            LogoutProcess.logout(context);
        } else {
            OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Interceptor.Chain chain) throws IOException {
                    Request original = chain.request();

                    Request request = original.newBuilder()
                            .header("Content-Type", "application/json")
                            .header("X-Requested-With", "XMLHttpRequest")
                            .header("X-Authorization", "Bearer " + TokenIdentifier.getTOKEN())
                            .method(original.method(), original.body())
                            .build();

                    return chain.proceed(request);
                }
            });

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

            OkHttpClient client = httpClient.build();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(Constant.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(client)
                    .build();

            ApiService apiService = retrofit.create(ApiService.class);
            Call<String> call = apiService.uploadImage(fileToUpload);
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, retrofit2.Response<String> response) {
                    if (response.body() != null && !response.body().isEmpty()) {
                        Snackbar.make(view, "Image uploaded", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                    }
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    t.printStackTrace();
                }
            });
        }

    }

如何解决此异常?

0 个答案:

没有答案