Android简单的获取网络上的json文件

设置网络访问权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.wangjialin.internet.json"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="8" />
<!-- 访问internet权限 -->
<uses-permission android:name="android.permission.INTERNET"/>

</manifest> 

布局文件:
mian.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<ListView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/listView"
    />
</LinearLayout>

布局文件:
item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content">

  <TextView
   android:layout_width="200dp"
   android:layout_height="wrap_content"
   android:id="@+id/title"
  />

    <TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/timelength"
  />
</LinearLayout>

编写主MainActivity文件,具体内容如下:

package com.wangjialin.internet.json;

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

import com.wangjialin.internet.json.domain.News;
import com.wangjialin.internet.json.service.NewsService;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView listView = (ListView) this.findViewById(R.id.listView);

        String length = this.getResources().getString(R.string.length);
        try {
            List<News> newes = NewsService.getJSONLastNews();
            List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
            for(News news : newes){
                HashMap<String, Object> item = new HashMap<String, Object>();
                item.put("id", news.getId());
                item.put("title", news.getTitle());
                item.put("timelength", length+ news.getTimelength());
                data.add(item);
            }
            SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
                    new String[]{"title", "timelength"}, new int[]{R.id.title, R.id.timelength});
            listView.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

MainActivity 的核心功能是获取数据并显示数据。
其中获取的数据内的NewsService的具体内容如下:

package com.wangjialin.internet.json.service;

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

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

import com.wangjialin.internet.json.domain.News;
import com.wangjialin.internet.json.utils.StreamTool;



public class NewsService {

    /**
     * 获取最新视频资讯
     * @return
     * @throws Exception
     */
    public static List<News> getJSONLastNews() throws Exception{
        String path = "http://192.168.1.100:8080/ServerForJSON/NewsListServlet";
        HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode() == 200){
            InputStream json = conn.getInputStream();
            return parseJSON(json);
        }
        return null;
    }

    private static List<News> parseJSON(InputStream jsonStream) throws Exception{
        List<News> list = new ArrayList<News>();
        byte[] data = StreamTool.read(jsonStream);
        String json = new String(data);
        JSONArray jsonArray = new JSONArray(json);
        for(int i = 0; i < jsonArray.length() ; i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            int id = jsonObject.getInt("id");
            String title = jsonObject.getString("title");
            int timelength = jsonObject.getInt("timelength");
            list.add(new News(id, title, timelength));
        }
        return list;
    }
}

在getJSONLastNews方法中是直接请求搭建好的web服务器,获取JSON输入流后,使用parseJSON方法解析XML数据并最终返回集合数据。
同时在NewsService中用到了一个JavaBean,用于封装XML数据,其名称News,具体内容如下所示:

package com.wangjialin.internet.json.domain;

public class News {
    private Integer id;
    private String title;
    private Integer timelength;
    public News(){}
    public News(Integer id, String title, Integer timelength) {
        this.id = id;
        this.title = title;
        this.timelength = timelength;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public Integer getTimelength() {
        return timelength;
    }
    public void setTimelength(Integer timelength) {
        this.timelength = timelength;
    }

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值