AsyncTask请求网络

本文介绍了一个使用Android中AsyncTask进行网络请求的例子。通过一个具体的天气查询应用,展示了如何在后台线程发起HTTP请求获取JSON数据,并解析数据来更新UI。此外,还介绍了如何加载图片到GridView。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.介绍一下AsyncTask请求网络的方法

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

	private String url = "http://op.juhe.cn/onebox/weather/query?cityname=%E5%8C%97%E4%BA%AC&dtype=&key=1a00070dffafe2c0a237e4b857b76ae4";
	private String url1 = "http://172.17.29.120/localuser/ljy/hengbo/data.json";
	private TextView contnet;
	private GridView girdView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		contnet = (TextView) findViewById(R.id.content);
		girdView = (GridView) findViewById(R.id.girdView);
		// 请求天气
		new Thread() {
			public void run() {
				try {
					URL k = new URL(url);
					HttpURLConnection con = (HttpURLConnection) k
							.openConnection();
					con.setConnectTimeout(2000);
					if (con.getResponseCode() == 200) {
						InputStream inputStream = con.getInputStream();
						ByteArrayOutputStream os = new ByteArrayOutputStream();
						int len = 0;
						byte[] buffer = new byte[1024];
						while ((len = inputStream.read(buffer)) != -1) {
							os.write(buffer, 0, len);
						}
						String json = os.toString();
						//
						JSONObject jsonObject = new JSONObject(json);
						JSONObject jsonObject2 = jsonObject
								.getJSONObject("result");
						JSONObject jsonObject3 = jsonObject2
								.getJSONObject("data");
						JSONObject jsonObject4 = jsonObject3
								.getJSONObject("realtime");
						JSONObject weather = jsonObject4
								.getJSONObject("weather");
						JSONObject wind = jsonObject4.getJSONObject("wind");
						// -------------------------------------------------
						final String temperature = weather
								.getString("temperature");
						final String info = weather.getString("info");
						final String direct = wind.getString("direct");
						final String power = wind.getString("power");
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								contnet.setText(info + "\n" + direct + power
										+ "\n" + temperature);
							}
						});
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
		// 使用AsyncTask請求網絡
		new MyAsyncTask().execute(url1);
	}

	// AsyncTask

	class MyAsyncTask extends AsyncTask> {

		@Override
		protected ArrayList doInBackground(String... params) {
			ArrayList list = new ArrayList();
			try {
				URL k = new URL(params[0]);
				HttpURLConnection con = (HttpURLConnection) k.openConnection();
				con.setConnectTimeout(2000);
				if (con.getResponseCode() == 200) {
					InputStream inputStream = con.getInputStream();
					ByteArrayOutputStream os = new ByteArrayOutputStream();
					int len = 0;
					byte[] buffer = new byte[1024];
					while ((len = inputStream.read(buffer)) != -1) {
						os.write(buffer, 0, len);
					}
					String json = os.toString();
					//
					JSONObject jsonObject = new JSONObject(json);
					JSONArray jsonArray = jsonObject.getJSONArray("data");
					for (int i = 0; i < jsonArray.length(); i++) {
						Classes classes = new Classes();
						JSONObject jsonObject2 = jsonArray.getJSONObject(i);
						classes.setTitle(jsonObject2.getString("title"));
						classes.setImage(jsonObject2.getString("image"));
						list.add(classes);
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(ArrayList result) {
			girdView.setAdapter(new MyAdapter(result));
		}
	}

	class MyAdapter extends BaseAdapter {

		private ArrayList list;

		public MyAdapter(ArrayList list) {
			this.list = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = View.inflate(MainActivity.this, R.layout.item, null);
			TextView item_title = (TextView) convertView
					.findViewById(R.id.item_title);
			ImageView item_iamge = (ImageView) convertView
					.findViewById(R.id.item_iamge);

			item_title.setText(list.get(position).getTitle());
			ImageLoader imageLoader = ImageLoader.getInstance();
			imageLoader.displayImage(list.get(position).getImage(), item_iamge);
			return convertView;
		}

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值