这篇文章主要介绍使用HttpClient获取网络数据,然后经过JSON后显示出来。另外本文章用到了常用的异步加载技术,AsyncTask类,该类其实是个封装好的线程池,使用起来比较方便。
实现效果图:
源代码:
布局文件:
activity_main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="@android:color/holo_purple"/>
</RelativeLayout>
代码文件:
MainActivity:
package com.weather4;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
/**
* 通过接口,获取网络的信息,然后经过JSON解析,显示在屏幕上。
* 方法二:
* (异步加载可以不用Handler或者是thread)
*
*/
public class MainActivity extends Activity {
private TextView mTextView;
private String url = "http://m.weather.com.cn/data/101010100.html";
protected CharSequence weatherResult = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textView01);
/**
* 使用异步加载技术。
*/
new RequestTask().execute();
}
private class RequestTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
/**
* 在doInBackground方法中,做一些诸如网络请求等耗时操作。
*/
return RequestData();
}
/**
* onPostExecute方法主要是主线程中的数据更新。
*/
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
//如果获取的result数据不为空,那么对其进行JSON解析。并显示在手机屏幕上。
JSONAnalysis(result);
} else if (result == null) {
Toast.makeText(MainActivity.this, "请求数据失败", Toast.LENGTH_LONG)
.show();
}
}
}
/**
* 网络请求,这里用的是HttpClient,区别于上一篇文章的HttpURLConnection。
* @return
*/
public String RequestData() {
HttpGet get = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
StringBuilder builder = null;
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
builder = new StringBuilder();
String s = null;
for (s = reader.readLine(); s != null; s = reader.readLine()) {
builder.append(s);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.toString();
}
/**
* 对请求回来的数据进行JSON解析。
* @param result
*/
public void JSONAnalysis(String result) {
JSONObject object = null;
try {
object = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject ObjectInfo = object.optJSONObject("weatherinfo");
String city = ObjectInfo.optString("city");
String date = ObjectInfo.optString("date_y");
String week = ObjectInfo.optString("week");
String temp = ObjectInfo.optString("temp1");
String weather = ObjectInfo.optString("weather1");
String index = ObjectInfo.optString("index_d");
weatherResult = "城市:" + city + "\n日期:" + date + "\n星期:" + week
+ "\n温度:" + temp + "\n天气情况:" + weather + "\n穿衣指数:" + index;
mTextView.setText(weatherResult);
}
}
源代码下载: