public class MyAsyncTask extends AsyncTask<String ,Integer ,Bitmap>{ @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); imgview.setImageBitmap(bitmap); } @Override protected Bitmap doInBackground(String... params) { String path = "http://p2.so.qhimgs1.com/sdr/200_200_/t01aa0205686cc0182e.jpg"; HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(path); try { //網絡請求對象得到響應 HttpResponse httpResponse = client.execute(get); //判斷狀態碼 if(httpResponse.getStatusLine().getStatusCode()==200){ InputStream inputStream = httpResponse.getEntity().getContent(); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } } catch (Exception e) { e.printStackTrace(); } return null; }
獲取json
public class TwoAsyncTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
//在這個方法中做耗時操作
//創建網絡請求對象
HttpClient client = new DefaultHttpClient();
//創建請求方式
String path = params[0];
HttpGet get = new HttpGet(path);
//網絡請求對象執行請求
try {
HttpResponse response = client.execute(get);
//判斷狀態碼
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
//從服務器獲取輸入流
InputStream inputStream = response.getEntity().getContent();
//定義一個字節數組輸出流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//定義一個字節字節數組
byte[] buffer = new byte[1024];
//定義長度
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
inputStream.close();
bos.close();
String json = bos.toString("utf-8");
return json;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Toast.makeText(MainActivity.this, "在onProgressUpdate方法中更新進度", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("xxx", s);
try {
//原生獲取對象
JSONObject jsonObject = new JSONObject(s);
//原生獲取集合
JSONArray data = jsonObject.getJSONArray("data");
//創建適配器 並構造傳參
MyAdapter adapter = new MyAdapter(MainActivity.this, data);
//設置適配器
lv.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}