You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
pocketcommunityclient/app/src/main/java/com/community/pocket/util/HttpFileResponse.java

52 lines
1.5 KiB

package com.community.pocket.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class HttpFileResponse implements Callback {
private static final String header = "Content-Type";
private final MutableLiveData<Bitmap> image;
public HttpFileResponse(MutableLiveData<Bitmap> image) {
this.image = image;
}
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
e.printStackTrace();
Log.e(HttpJSONResponse.class.getName(), e.toString());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) {
String contentType = response.header(header);
if ("image/png".equals(contentType)) {
ResponseBody responseBody = response.body();
if (responseBody != null) {
Bitmap bitmap = BitmapFactory.decodeStream(responseBody.byteStream());
image.postValue(bitmap);
}
} else {
onParseError(call, response, "接口不是响应图片数据,非法响应头" + header + "=" + contentType);
}
}
private void onParseError(@NotNull Call call, @NotNull Response response, String err) {
Log.e(HttpJSONResponse.class.getName(), err);
throw new RuntimeException(err);
}
}