AsyncTask异步加载和HttpURLConnection网络请求数据
Posted 巫山码农
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AsyncTask异步加载和HttpURLConnection网络请求数据相关的知识,希望对你有一定的参考价值。
//获得网络数据
private void huodeshuju() {
//这里是使用线程,已注释掉
/*new Thread(){
public void run() {
try {
URL url=new URL(urlPath);
HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int code=urlConnection.getResponseCode();
if (code==200) {
InputStream inputStream=urlConnection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer buffer=new StringBuffer();
while ((line=reader.readLine())!=null) {
buffer.append(line);
}
String str=buffer.toString();
Message message=new Message();
message.what=0;
message.obj=str;
handler.sendMessage(message);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();*/
//----------下面是使用的异步加载-----------------------------
new AsyncTask<String, Void, String>(){
@Override
protected String doInBackground(String... params) {
try {
URL url=new URL(params[0]);
HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int code=urlConnection.getResponseCode();
if (code==200) {
InputStream inputStream=urlConnection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
String readerline;
StringBuffer buffer=new StringBuffer();
while ((readerline=reader.readLine())!=null) {
buffer.append(readerline);
}
String str=buffer.toString();
return str;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
try {
JSONObject obj=new JSONObject(result);
JSONArray data=obj.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject json=data.getJSONObject(i);
String id=json.getString("id");
String goods_name=json.getString("goods_name");
String shop_price=json.getString("shop_price");
String market_price=json.getString("market_price");
String is_coupon_allowed=json.getString("is_coupon_allowed");
String is_allow_credit=json.getString("is_allow_credit");
String goods_img=json.getString("goods_img");
String sales_volume=json.getString("sales_volume");
String efficacy=json.getString("efficacy");
Goods goodss=new Goods(id, goods_name, shop_price,
market_price, is_coupon_allowed, is_allow_credit, goods_img,
sales_volume, efficacy);
goods.add(goodss);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.execute(urlPath);//urlpath为网址
}
以上是关于AsyncTask异步加载和HttpURLConnection网络请求数据的主要内容,如果未能解决你的问题,请参考以下文章
AsyncTask异步加载和HttpURLConnection网络请求数据
AsyncTask异步加载和HttpURLConnection网络请求数据