我在专用于执行spring android请求的线程中使用spring android.
我无法实现终止从Spring android(例如getForObject)启动的请求.
我试过了 :
>到达基础输入流以关闭,但已完全包装在springandroid restemplate中,无法从外部访问
>中断线程
>获取其余模板的请求工厂并调用destroy
>获得工厂的连接管理器并致电关机
>更改其余模板工厂的http客户端
>更改其余模板工厂的请求工厂
但我无法中止请求并快速发送新请求.第一个必须达到其超时.
我如何“杀死”一个春季android请求以获得稳定的rest模板以发送新请求?
提前致谢.
解决方法:
我建议使用ResponseExtractor.
您可以调用RestTemplate的execute方法,如下所示.
File file = (File) restTemplate.execute(rootUrl.concat("/vocasets/{vocasetId}/{version}"), HttpMethod.GET, requestCallabck,
responseExtractor, uriVariables);
ResponseExtractor具有extractData方法.您可以通过响应的getBody()从extractData方法获取主体输入流.
扩展ResponseExtractor以取消您的请求.
祝好运.
就我而言,我使用了侦听器方式.
static class FileResponseExtractor implements ResponseExtractor<File> {
...
public void setListener(ReceivingListener listener) {
this.listener = listener;
}
@Override
public File extractData(ClientHttpResponse response) throws IOException {
InputStream is = response.getBody();
long contentLength = response.getHeaders().getContentLength();
long availableSpace = AvailableSpaceHandler.getExternalAvailableSpaceInMB();
long availableBytes = AvailableSpaceHandler.getExternalAvailableSpaceInBytes();
Log.d(TAG, "available space: " + availableSpace + " MB");
long spareSize = 1024 * 1024 * 100;
if(availableBytes < contentLength + spareSize) {
throw new NotEnoughWritableMemoryException(availableSpace);
}
File f = new File(temporaryFileName);
if (f.exists())
f.delete();
f.createNewFile();
OutputStream o = new FileOutputStream(f);
listener.onStart(contentLength, null);
boolean cancel = false;
try {
byte buf[] = new byte[bufferSize];
int len;
long sum = 0;
while ((len = is.read(buf)) > 0) {
o.write(buf, 0, len);
sum += len;
listener.onReceiving(sum, len, null);
cancel = !listener.onContinue();
if(cancel) {
Log.d(TAG, "Cancelled!!!");
throw new CancellationException();
}
}
} finally {
o.close();
is.close();
listener.onFinish(null);
if(cancel) {
f.delete();
}
}
return f;
}
}