Android网络请求,获取数据,解析数据Demo

添加依赖 

build.gradle

dependencies {
    compile 'com.google.code.gson:gson:2.4'
}

右上角Sync Now


在AndroidManifest.xml中添加网络访问权限

    <uses-permission android:name="android.permission.INTERNET"/>

主页面布局

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.httpdemo.MainActivity">
    <TextView
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:text="慕课"
        android:textSize="28sp"
        android:gravity="center"
        android:textColor="#ffffff"
        android:background="#3f51b5"
        android:paddingRight="15dp"/>
    <ImageView
        android:id="@+id/banner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"/>
    <ListView
        android:id="@+id/essay_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>
</LinearLayout>

被跳转页面布局

activity_detail.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_detail"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:showIn="@layout/activity_detail"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:gravity="center"
        android:layout_marginTop="15dp" />

    <TextView
        android:id="@+id/author"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:gravity="right"
        android:paddingRight="10dp"
        android:layout_marginTop="15dp"/>

    <TextView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="8dp"
        android:layout_marginTop="15dp"
        android:layout_weight="1"
        android:lineSpacingMultiplier="1.5"
        android:textSize="20sp" />
</LinearLayout>

数据实体类

Essay.java

package com.administrator.hellodemo;



public class Essay {
    private String title;
    private String author;
    private String content;

    public Essay(String title, String author, String content) {
        this.title = title;
        this.author = author;
        this.content = content;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

主页面Java代码

MainActivity.java

package com.administrator.hellodemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    private void initView() {
        findViewById(R.id.header).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,DetailActivity.class));
            }
        });
    }
}

被跳转页Java代码

package com.administrator.hellodemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.gson.Gson;

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

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DetailActivity extends Activity {
    private TextView nameView,authorView,contentView;
    private int id;
    private Handler handler = new Handler(){
        @Override

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Essay e = (Essay) msg.obj;
            nameView.setText(e.getTitle());
            authorView.setText(e.getAuthor());
            contentView.setText(e.getContent());

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

        Intent it = getIntent();
        id = it.getIntExtra("essay",1);
        initView();
        initData();
    }

    public void initView(){
        nameView = (TextView) findViewById(R.id.name);
        authorView = (TextView) findViewById(R.id.author);
        contentView = (TextView) findViewById(R.id.content);
    }

    public void initData(){
        //HttpUrlConnection
        /**
         * 1.实例化一个url对象
         * 2.获取HttpUrlConnection对象
         * 3.设置请求连接属性
         * 4.获取响应码,判断是否连接成功
         * 5.读取输入流并解析
         */
        //参数:你要访问的接口地址
        new Thread(){
            @Override
            public void run() {
                try {
                    URL url = new URL("http://www.imooc.com/api/teacher?type=3&cid="+id );
                    HttpURLConnection coon = (HttpURLConnection) url.openConnection();
                    coon.setRequestMethod("GET");
                    coon.setReadTimeout(6000);
                    //获取响应码
                    if(coon.getResponseCode() == 200){
                        //获取输入流
                        InputStream in = coon.getInputStream();
                        byte[] b = new byte[1024*512];
                        int len = 0;
                        //建立缓存流,保存所读取的字节数组
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while ((len = in.read(b)) > -1){
                            baos.write(b,0,len);
                        }
                        String msg = baos.toString();
                        Log.e("TAG",msg);
                        //JSON数据的解析:
                        JSONObject obj = new JSONObject(msg);

                        //HashMap map = null;
                        //map.get("age")
                        int status = obj.getInt("status");
                        String msg2 = obj.getString("msg");
                        Log.e("TAG",status + "   " + msg2);

                        //1.创建Gson对象
                        Gson gson = new Gson();
                        //参数1:满足json对象格式的字符串
                        String data = obj.getString("data");
                        Essay e = gson.fromJson(data,Essay.class);



                        /*JSONObject data = obj.getJSONObject("data");
                        String title = data.getString("title");
                        String author = data.getString("author");
                        String content = data.getString("content");
                        Log.e("TAG","标题:" + title + ",作者:" + author + ",内容:" + content);*/
                        //将操作权交还给主线程

                        Message message = handler.obtainMessage();
                        //Essay e = new Essay(title,author,content);
                        message.obj =e;

                        //调用此方法,则会触发主线程中Handle对象里覆盖了的handleMessage方法
                        handler.sendMessage(message);

                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();



    }


}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值