java - 如何在 android 中使用 HttpURLConnection 启用缓存?
问题描述
如何使用 java 在 android 中使用 HttpURLConnection 启用缓存?
这是我的源代码:
public class GetMenuData extends AsyncTask<String , Void ,String> {
String server_response;
@Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setDoInput(true);
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject res = new JSONObject(server_response);
//get json array
JSONArray Jarray = res.getJSONArray("menu");
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
MenuItem n = new MenuItem(
object.getInt("ID"),
object.getString("title"),
object.getString("image"));
Log.e("TAG", "" + n.getId());
itemsToolbar_Menu.add(n);
}
mViewPager.setAdapter(mSectionsPagerAdapter);
setupTabLayout(toolbarAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
主要活动
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ToolbarAdapter toolbarAdapter;
private ViewPager mViewPager;
private ArrayList<MenuItem> itemsToolbar_Menu;
private SectionsPagerAdapter mSectionsPagerAdapter;
private GetMenuData iData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemsToolbar_Menu = new ArrayList<>();
mViewPager = findViewById(R.id.container);
tabLayout = findViewById(R.id.tabs);
//Request Data
iData = new GetMenuData();
iData.execute(URL_MENU);
}
它工作正常,但是当我在没有互联网连接的情况下在模拟器上运行应用程序时,它给了我这个错误
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“int java.lang.String.length()”
解决方案
推荐阅读
- python - 为什么使用 Oracle_cx 时显示“无效长度”错误消息?
- excel - 工作表的类型不匹配错误..无法修复
- c# - 在 ViewModel 类 C# 中实例化模型类的麻烦
- sql - 交叉列之间的减法
- excel - SQL 获取错误 91 对象变量或 With 块的 VBA 更新语句
- node.js - 如何用 jest 设置媒体查询?
- bash - 在变量中存储值会增加一个字符的长度
- python - 从不同的列表框条目中获取数据以调用单个函数
- c# - 使用 c# 的 Visual Studio 中的 MSSQL 删除代码正在运行,但是当我重新启动时它会恢复到原始状态
- javascript - 如何在第一页浏览本地文件中的视频并在第二页播放?