陈斌彬的技术博客

Stay foolish,stay hungry

Android Webservice 入门学习

测试使用百度API-天狗医生大全API

img

img

img

img

目录结构

img

接口地址

http://apistore.baidu.com/astore/classificationservicelist/119.html

代码地址

https://github.com/cnbin/androidDemo/tree/master/webservice/%E7%99%BE%E5%BA%A6API-%E5%A4%A9%E7%8B%97%E5%8C%BB%E7%94%9FAPIDemo

MainActivity

package com.jikexueyuan.news;

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

import com.jikexueyuan.news.adapter.NewsAdapter;
import com.jikexueyuan.news.model.News;
import com.jikexueyuan.news.utils.HttpUtils;

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

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

public class MainActivity extends Activity {

    private ListView lvNews;
    private NewsAdapter adapter;
    private List<News> newsList;

    public static  String GET_NEWS_URL = "http://apis.baidu.com/tngou/hospital/feature?id=1";

    private Handler getNewsHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            String jsonData = (String) msg.obj;
            System.out.println(jsonData);

            try {
                boolean jsonObj = new JSONObject(jsonData).optBoolean("status");
                System.out.println(jsonObj);

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

            try {
                JSONArray jsonArray = new JSONObject(jsonData).getJSONArray("tngou");
                for (int i=0;i<jsonArray.length();i++){
                    JSONObject object = jsonArray.getJSONObject(i);
                    String id = object.getString("id");
                    String message = object.getString("message");
                    newsList.add(new News(id, message));
                    System.out.println(newsList);
                }
                adapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lvNews = (ListView) findViewById(R.id.lvNews);
        newsList = new ArrayList<News>();
        adapter = new NewsAdapter(this, newsList);

        lvNews.setAdapter(adapter);
        HttpUtils.getNewsJSON(GET_NEWS_URL, getNewsHandler);
    }

}

HttpUtils

package com.jikexueyuan.news.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

public class HttpUtils {

    public static void getNewsJSON(final String url, final Handler handler){

        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn;
                InputStream is;
                try {
                    conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("apikey",  "c33bdd6ad06c082a12a171edc323cc9a");
                    is = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String line = "";
                    StringBuilder result = new StringBuilder();
                    while ( (line = reader.readLine()) != null ){
                        result.append(line);

                    }
                    Message msg = new Message();
                    msg.obj = result.toString();
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                } 
            }
        }).start();
    }

    public static void setPicBitmap(final ImageView ivPic, final String pic_url){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpURLConnection conn = (HttpURLConnection) new URL(pic_url).openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    ivPic.setImageBitmap(bitmap);
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                } 
            }
        }).start();
    }

}

NewsAdapter

package com.jikexueyuan.news.adapter;


import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.jikexueyuan.news.R;
import com.jikexueyuan.news.model.News;
import com.jikexueyuan.news.utils.HttpUtils;

public class NewsAdapter extends BaseAdapter {

    private Context context;
    private List<News> newsList;

    public NewsAdapter(Context context, List<News> newsList){
        this.context = context;
        this.newsList = newsList;
    }

    @Override
    public int getCount() {
        return newsList.size();
    }

    @Override
    public News getItem(int position) {
        return newsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.news_item, null);
        }
        TextView tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
        TextView tvDesc = (TextView) convertView.findViewById(R.id.tvDesc);


        News news = newsList.get(position);
        tvTitle.setText(news.getTitle());
        tvDesc.setText(news.getDesc());


        return convertView;
    }
}

News

package com.jikexueyuan.news.model;

public class News {

    private String title;
    private String desc;


    public News(String title, String desc){
        setTitle(title);
        setDesc(desc);

    }

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }

}