首页 > 解决方案 > 如何在 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()”

标签: javaandroidcachinghttpurlconnection

解决方案


推荐阅读