本人菜鸟一枚,第一次写博客,就想谈谈这个乱码问题,因为只要一出现乱码,大家首先想到的肯定是编码格式,改变编码格式的方法其实挺多的,这里我就展示一下我在写代码时遇到的乱码情况和坑点。
话不多说,直接上代码。
public class MyAsyncTask extends AsyncTask { private Gson gson; @Override protected Object doInBackground(Object[] objects) { try { gson = new Gson(); URL url = new URL((String) objects[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(3000); connection.setConnectTimeout(3000); if (connection.getResponseCode() == 200) { InputStream inputStream = connection.getInputStream(); Addbean addbean = gson.fromJson(new InputStreamReader(inputStream,"gbk"), Addbean.class); List<Addbean.ContentsBean> contents = addbean.getContents(); return contents; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }注:(代码中红色部分不是报错而是需要注意的地方!)网络请求我用的是AsyncTask+HttpURLConnection,然而在接收解析完的数据后发生了乱码现象,当时楼主也是很纠结,于是乎就去百度,可是转来转去不是楼主看不懂就是没有用。最后忽然发现InputStreamReader的方法里在转流的时候,可以在后面跟上自己想要的编码格式,这样就好了。其实有时候解决问题的办法就在自己敲得代码中,只要认真找,一定可以解决问题。这是我第一次发博客,希望大家可以留下宝贵的意见,在这里先谢谢了。