首页 > 解决方案 > 如果响应在android中包含分号,则改造response.body返回截断的字符串

问题描述

我正在尝试使用改造上传图像(这是我的第一次尝试),一切正常,但我的响应正文被截断并得到 12345 而不是“12345;fileName.jpg”。

我尝试转换response.body().toString()但仍然无法正常工作

Something.java (实现类)

标题

import retrofit2.converter.gson.GsonConverterFactory; 
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

执行

File file = new File(filePath);

//creating request body for file
RequestBody requestFile = RequestBody.create(MediaType.parse(fileType), file);

//The gson builder
Gson gson = new GsonBuilder()
        .setLenient()
        .create();

//creating retrofit object
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(this.getString(R.string.pref_upload_url))
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

//creating our api
Api api = retrofit.create(Api.class);

//creating a call and calling the upload image method
Call<String> call = api.uploadImage(requestFile);

//finally performing the call
call.enqueue(new Callback<String>() {
    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        String val = response.body().toString();
        if (response.body() != null && response.body().length() > 0 && response.body().charAt(0) != '0') {
            Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
    }
});

api.java

package com.ericsson.wfmmobileapp.android;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

public interface Api {

    @Multipart
    @POST("upload.php/")
    Call<String> uploadImage(@Part("file\"; filename=\"myfile.jpg\" ") RequestBody file);
}

邮递员输出

在此处输入图像描述

标签: androidretrofitretrofit2okhttpokhttp3

解决方案


感谢@Sayad Jafari,他提供了线索。

GsonConverterFactory是以 JSON 格式获得响应,分号(;)是行终止符号,所以我得到响应字符串直到分号,我改变了我使用的方法,ScalarsConverterFactory而不是GsonConverterFactory,现在它正在工作。

旧标题

import retrofit2.converter.gson.GsonConverterFactory; 
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

新标题

import retrofit2.converter.scalars.ScalarsConverterFactory;

旧实现

//The gson builder
Gson gson = new GsonBuilder()
        .setLenient()
        .create();

//creating retrofit object
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(this.getString(R.string.pref_upload_url))
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

新实施

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(this.getString(R.string.pref_upload_url))
        .addConverterFactory(ScalarsConverterFactory.create())
        .build();

推荐阅读