多次通过okhttpclient从后端加载图片,导致socket is closed。有什么解决方吗码?保持长连接不行
public Bitmap getImageBitMap(String imgUrl) throws IOException {
Bitmap bitmap;
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(imgUrl)
.build();
Response response = okHttpClient.newCall(request).execute();
byte[] bytes = Objects.requireNonNull(response.body()).bytes();
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bitmap;
}
@lzs1024
我没改okhttpcient以及后端代码。我也不知道,后来就好了。
为spinner绑定了onItemSelected,然后再调用线程。
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
Thread thread1 = new Thread(runnable1);
thread1.start();
break;
case 1:
Thread thread2 = new Thread(runnable2);
thread2.start();
break;
case 2:
// 暂时不支持
break;
case 3:
Thread thread4 = new Thread(runnable4);
thread4.start();
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
然后在线程中,调用了okhttpclient
Runnable runnable1 = new Runnable() {
@Override
public void run() {
productOkHttp http = new productOkHttp();
try {
List<product> products = http.getProduct();
handleData(products,http);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
貌似不是okhttpclient的问题,现在已经能够正常运行了
@yassin999
后端获取图片的代码
@Configuration
public class WebMvcConfigure extends WebMvcConfigurationSupport {
private static final Logger logger = LoggerFactory.getLogger(WebMvcConfigure.class);
@Value("${uploadFilePath}")
private String uploadFilePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
logger.info(uploadFilePath);
//和页面有关的静态目录都放在项目的static目录下
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
//上传的图片路径
registry.addResourceHandler("/uploaded/**").addResourceLocations("file:" + uploadFilePath);
}
}
我试了下你这代码多次下载没问题啊。是不是后端图片下载接口有问题?