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();
}