我正在尝试使用翻新2分段请求和Gson解析器将图像上传到服务器 我通过邮递员测试了api,它的工作正常,但是在android中,我遇到了提到的异常
这是我的代码
这是改造依赖
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
Api客户端
public class ApiClient {
public static final String BASE_URL = "http://www.AAbd.com/api/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
Gson gson = new GsonBuilder()
.create();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
Api接口
@POST("edit/Image")
@Multipart
Call<AuthModel> addImage (@Part("api_token") RequestBody api_token,
@Part("image") MultipartBody.Part image);
型号
@Expose
@SerializedName("api_token_status")
private String api_token_status;
@Expose
@SerializedName("status")
private String status;
@Expose
@SerializedName("message")
private String message;
public String getMessage() {
return message;
}
public String getApi_token_status() {
return api_token_status;
}
public String getStatus() {
return status;
}
调用请求
public void addImageRequest (Bitmap image) {
try {
File f = new File(getCacheDir(), "offf");
f.createNewFile();
Bitmap bitmap = image;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), f);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", f.getName(), reqFile);
RequestBody tokenRequest = RequestBody.create(MediaType.parse("text/plain"), token2);
apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<AuthModel> call = apiInterface.addImage(tokenRequest, body);
call.enqueue(new Callback<AuthModel>() {
@Override
public void onResponse(Call<AuthModel> call, Response<AuthModel> response) {
AuthModel result = response.body();
if(result != null) {
String status = result.getStatus();
String msg = result.getMessage();
if(status.equals("true")) {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
Log.e("errorIs", msg);
} else {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
Log.e("errorIs", msg);
}
} else {
try {
//Toast.makeText(context, response.errorBody().string() , Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<AuthModel> call, Throwable t) {
Toast.makeText(MainActivity.this, t.toString(), Toast.LENGTH_LONG).show();
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
我检查了以前有关此问题的所有问题,但没有找到适合我的情况的解决方案。请先帮助并谢谢