Java HTTP响应缓存在Android客户端中
我有以下情况:Java HTTP响应缓存在Android客户端中,java,android,json,apache,http,Java,Android,Json,Apache,Http,我有以下情况: 正在向我的远程服务器发送http post(post数据包含json字符串)请求 正在json中从我的服务器获取http post响应:{“result”:true} 断开我的平板电脑中的所有internet连接 重复步骤1中描述的post请求 正在获取相同的缓存“响应”-{“result”:true},这是我不希望得到的。。。我不希望我的http客户端缓存任何数据。我希望得到空值或类似的东西 如何防止http客户端缓存数据 我的服务处理程序如下所示: public String
public String makeServiceCall(String url, int method,
List<NameValuePair> params, String requestAction) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
}
else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
// Toast.makeText(Globals.getContext(), "check your connection", Toast.LENGTH_SHORT).show();
}
return response;
}
公共字符串makeServiceCall(字符串url,int方法,
列表参数、字符串请求操作){
试试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpEntity HttpEntity=null;
HttpResponse HttpResponse=null;
//检查http请求方法类型
if(方法==POST){
HttpPost HttpPost=新的HttpPost(url);
//添加post参数
如果(参数!=null){
setEntity(新的UrlEncodedFormEntity(参数));
}
httpResponse=httpClient.execute(httpPost);
}
else if(方法==GET){
//将参数附加到url
如果(参数!=null){
String paramString=URLEncodedUtils
.格式(参数“utf-8”);
url+=“?”+参数字符串;
}
HttpGet HttpGet=新的HttpGet(url);
httpResponse=httpClient.execute(httpGet);
}
httpEntity=httpResponse.getEntity();
response=EntityUtils.toString(httpEntity);
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
//Toast.makeText(Globals.getContext(),“检查您的连接”,Toast.LENGTH_SHORT.show();
}
返回响应;
}
我刚刚注意到response
是一个成员变量。为什么需要一个成员变量来返回此结果。您可能在第二次尝试时返回相同的结果。重新抛出捕获的异常,让调用方处理它 Post响应并不意味着要缓存。您是如何得出响应被缓存的结论的?我正在检查logcat日志。当我断开互联网并尝试发出请求时,我看到的是以前的响应值(当互联网仍在工作时),而不是空值或类似的值。啊!我刚刚注意到response
是一个成员变量。为什么需要一个成员变量来返回此结果。您可能在第二次尝试时返回相同的结果。重新抛出捕获的异常,让调用方处理它。让我知道这是否解决了问题。谢谢你的提示!我解决了我的问题。异常之一是抛出,因此我返回“旧”响应值。将返回值设为null并在异常处理程序上方添加额外的返回行解决了我的问题。不客气。我已经把答案从评论部分移到了答案部分。