字节流转换字符流
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new XML().execute("null");
}
public class XML extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
// URL u = new URL("http://download.oracle.com/technetwork/java/javase/6/docs/zh/api.zip");
URL u = new URL("http://cdefgab.web.fc2.com/song.json");
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setConnectTimeout(3000);
huc.setReadTimeout(3000);
huc.setDoInput(true);
huc.setRequestMethod("GET");
// 字节流转换字符流方法
// if(huc.getResponseCode() == 200) {
// BufferedReader br = new BufferedReader(new InputStreamReader(huc.getInputStream(),"utf-8"));
// InputStream is = huc.getInputStream();
// InputStreamReader isr = new InputStreamReader(is,"utf-8");
// BufferedReader br = new BufferedReader(isr);
// String temp = null;
// while((temp = br.readLine()) != null){
// System.out.println("--------------");
// System.out.println(temp);
// }
// }
// 字节流缓冲方法
if (huc.getResponseCode() == 200) {
System.out.println("-----Astart");
BufferedInputStream bis = new BufferedInputStream(huc.getInputStream());
int i = 0;
byte[] buff = new byte[1024];
while ((i = bis.read(buff)) != -1) {
System.out.println("deta.length--" + i);
System.out.println(new String(buff, 0, i));
}
System.out.println("-----Aend");
}
if (huc.getResponseCode() == 200) {
System.out.println("-----Bstart");
InputStream is = huc.getInputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len = is.read(buff)) != -1) {
System.out.println("data.lenght" + len);
System.out.println(new String(buff, 0, len));
}
System.out.println("-----Bend");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
1 件のコメント:
字节流转换字符流时需要设置编码 如 utf-8
コメントを投稿