您的位置:首页 > 理论基础 > 计算机网络

Android 实时加载网络新闻

2016-08-17 20:35 309 查看
[b]实现效果:在Spinner中加载一个下拉列表,显示出所有类型新闻。[/b]

                   点击每一种类型的新闻,在布局的TestView中显示出具体内容。

首先写两个实体类,分别是从网络获取新闻的实体类和获取新闻接口的实体类。然后在activity中调用。

1.HttpUtil代码

package com.example.administrator.jreduch09.Class;

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;

public class HttpUtil {
public static String GetHttp(String params){
BufferedReader reader=null;
HttpURLConnection con = null;
InputStream is = null;
StringBuilder sbd = new StringBuilder();
String str="";
try {
URL url = new URL(params);
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("apikey","5b46143955a4b1ff1b470a94315625cd");
con.setConnectTimeout(5 * 1000);
con.setReadTimeout(5 * 1000);
if (con.getResponseCode() == 200) {
is = con.getInputStream();
reader=new BufferedReader(new InputStreamReader(is,"UTF-8"));
while ((str=reader.readLine())!=null){
sbd.append(str);
sbd.append("\r\n");
}
}
} 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 sbd.toString();
}
}
2.UrlUtil代码:

package com.example.administrator.jreduch09.Class;

public class UrlUtil {

//获取 频道的网络接口
public  static String channelUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/channel_news";
/*获取 频道对应新闻的网络接口
get 请求参数:
channelId    : 新闻频道id,必须精确匹配
channelName  :新闻频道名称,可模糊匹配
title        :新闻标题,模糊匹配
page         :页数,默认1。每页最多20条记
needContent  : 是否需要返回正文,1为需要
needHtml     :是否需要返回正文的html格式,1为需要
*/
public  static String newsUrl = "http://apis.baidu.com/showapi_open_bus/channel_news/search_news";

}
主布局:

<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.example.administrator.jreduch09.HttpJsonActivity">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/channel">
</Spinner>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/channel">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/show"/>
</ScrollView>
</RelativeLayout>
代码:

package com.example.administrator.jreduch09;

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.jreduch09.Class.HttpUtil;
import com.example.administrator.jreduch09.Class.UrlUtil;
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 HttpJsonActivity extends AppCompatActivity {
private TextView show;
private Spinner channel;
private SimpleAdapter sa;
private List<Map<String,String>> channelList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_json);
channel= (Spinner) findViewById(R.id.channel);
show= (TextView) findViewById(R.id.show);
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 GetChannel().execute();
channel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Map map=channelList.get(position);
map.get("name");
String  channelName = (String) map.get("name");
String channelId = (String) map.get(channelName);
String url=UrlUtil.newsUrl+"?channelId="
+channelId+"&channelName="+channelName+"&needContent=1"
+"needHtml=1";
new GetNews().execute(url);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

}
public class GetChannel extends AsyncTask<String,Void,String>{

@Override
protected String doInBackground(String... params) {
return HttpUtil.GetHttp(UrlUtil.channelUrl);
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s.equals("")){
Toast.makeText(getBaseContext(),"网络加载异常",Toast.LENGTH_SHORT).show();
return;
}
try {
JSONObject obj=new JSONObject(s);
JSONObject obj1= obj.getJSONObject("showapi_res_body");
JSONArray ja=obj1.getJSONArray("channelList");
for(int i=0;i<ja.length();i++){
JSONObject channelObj= (JSONObject) ja.get(i);
String name=channelObj.getString("name");
String id=channelObj.getString("channelId");
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(
4000
String... params) {
return HttpUtil.GetHttp(params[0]);
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
show.setText(s);
if(s.equals("")){
show.setText("没有数据");
return;
}else {
show.setText(s);
}
}
}
}
完成效果:






内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android 网络