从网络获取数据,解析后输出。

我们要做的是从网络获取数据,在Activity中显示出来。

首先我们要导入gson包,它的作用是把Json字符串转换成相等的Java对象。把从网络获取数据和保存数据的方法写成类,方便以后调用。

import java.io.BufferedReader;               //从网络获取数据
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
* Created by Administrator on 2016/8/17.
*/
public class HttpUtil {
public static String HttpGet(String params){
{
HttpURLConnection con=null; //HttpURLConnection获取数据的方法

InputStream is = null; //输入流
BufferedReader reader=null; //包装字符流到缓存里,优化程序
StringBuffer sbf=new StringBuffer(); //字符串变量,它的对象是可以扩充和修改的。
try {
URL url=new URL(params); //params为网址
                con  = (HttpURLConnection)url.openConnection();
con.setConnectTimeout(5 * 1000);
con.setReadTimeout(5*1000);
con.setRequestProperty("apiKey", "5b46143955a4b1ff1b470a94315625cd");
con.connect();
if(con.getResponseCode()==200){
is = con.getInputStream();
reader=new BufferedReader(new InputStreamReader(is));
String strRead=null;
while((strRead=reader.readLine())!=null){
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
return sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is!= null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(con!=null){
con.disconnect();
}
}
return "";

}


}
}



public class UrlUtil {
//获取频道的网络接口
public static String channelUrl="http://apis.baidu.com/showapi_open_bus/channel_news/channel_news";
/* 获取频道对应新闻的网络接口
/ get请求参数
channelId : 新闻频道ID ,必须匹配精确
channelName : 新闻频道名称,可模糊匹配
title : 新闻标题,可模糊匹配
page : :页数
needContent :是否需要返回正文 1 需要
needHtml : 是否需要返回html格式的正文 1 需要
*/
public static String newsUrl="http://apis.baidu.com/showapi_open_bus/channel_news/search_news";
}
//Activity中的代码
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.jreduch07.R;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class APIActivity extends AppCompatActivity {
private TextView textView; //用于显示数据
private Spinner channel; //下拉列表
private SimpleAdapter sa; //适配器
private List<Map<String ,String>> channelList; //范型存放的是Map,Map中存放的是两个String类型的数据

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_api);
textView= (TextView) findViewById(R.id.textView);
channel= (Spinner) findViewById(R.id.channel);
channelList=new ArrayList<>();
sa=new SimpleAdapter(this,channelList,
android.R.layout.simple_spinner_item,
new String[]{"name"},new int[] {android.R.id.text1});
channel.setAdapter(sa);
new GetChanel().execute();
channel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Map<String,String> map= channelList.get(position);
String channelName= map.get("name");
String channelId=map.get(channelName);
String url=UrlUtil.newsUrl
+"?channelId="
+channelId+"&channelName="+channelName;
new GetNews().execute(url);
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}
});


}


//获取频道
public class GetChanel extends AsyncTask<Void,Void,String>{
@Override
protected String doInBackground(Void... params) {
return HttpUtil.HttpGet(UrlUtil.channelUrl);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s.equals("")){
Toast.makeText(getBaseContext(),"没有数据",Toast.LENGTH_SHORT).show();
}
try {
JSONObject obj=new JSONObject(s);
JSONObject body=obj.getJSONObject("showapi_res_body");
JSONArray ja=body.getJSONArray("channelList");
for(int i=0;i<ja.length();i++){
JSONObject channelObj= (JSONObject) ja.get(i);
String id=channelObj.getString("channelId");
String name=channelObj.getString("name");
Map map=new HashMap();
map.put("name",name);
map.put(name,id);
channelList.add(map);
}
sa.notifyDataSetChanged();

} catch (JSONException e) {
e.printStackTrace();
}
}
}

//获取新闻
public class GetNews extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... params) {
return HttpUtil.HttpGet(params[0]);
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s.equals("")){
textView.setText("没有");
}
textView.setText(s);
}
}

}
 
posted @ 2016-08-17 20:30  头一回  阅读(818)  评论(0编辑  收藏  举报