资讯_HttpConnect+Handler请求数据

AndroidManifest.xml写权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.day01sa">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<!--网络权限-->
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity

package com.example.day01sa;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.day01sa.bean.JsonBean;
import com.example.day01sa.http.Http;
import com.google.gson.Gson;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取控件
        Button button = findViewById(R.id.button);
        //点击事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        //进行耗时操作
                        //判断网络状态
                        boolean networkHttp = Http.isNetworkHttp(MainActivity.this);
                        if (networkHttp){
                            //获取路径
                            String get = Http.requestHttpGET("http://api.expoon.com/AppNews/getNewsList/type/1/p/1");
                            //创建Gson对象
                            Gson gson = new Gson();
                            //进行解析
                            JsonBean jsonBean = gson.fromJson(get,JsonBean.class);
                            //创建message对象,并把数据传输到handler
                            Message  message = new Message();
                            message.what = 0;
                            message.obj = jsonBean;
                            handler.sendMessage(message);

                        }else{

                            handler.sendEmptyMessageDelayed(1,0);

                        }
                    }
                }.start();
            }
        });

    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    //获取数据
                    JsonBean bean = (JsonBean) msg.obj;
                    //吐丝
                    Toast.makeText(MainActivity.this,""+bean.toString(),Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Toast.makeText(MainActivity.this,"兄嘚,木网啊!!!",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

}

Http

package com.example.day01sa.http;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

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

public class Http {

    public static boolean isNetworkHttp(Context context) {
        //写网络权限
        //注意参数是否为空
        if (context != null) {
            //getSystemService获取系统服务
            //获取连接管理器
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取网络状态
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info != null) {
                //判断网络是否可用
                return info.isAvailable();
            }
        }
        return false;
    }

    public static  String requestHttpGET(String strurl){

        try {
            //设置url
            URL url = new URL(strurl);
            //获取httpurlconnetion
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置get请求
            connection.setRequestMethod("GET");
            //设置连接主机超时时间
            connection.setConnectTimeout(5000);
            //设置从主机获取数据超时
            connection.setReadTimeout(5000);
            //获取请求码
            int code = connection.getResponseCode();
            //判断是否成功
            if (code == HttpURLConnection.HTTP_OK){
                //获取数据
                InputStream stream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream,"utf-8"));
                //拼接字符
                StringBuilder builder = new StringBuilder();
                //把数据读取成字符串
                String str = "";

                while ((str = reader.readLine())!=null){
                    //把一行行拼接成一行
                    builder.append(str);
                }
                //返回拼接后的数据
                return builder.toString();
            }
            //关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

注意:注意:导包build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.qy.day01"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    //导入的Gson库
    implementation 'com.google.code.gson:gson:2.2.4'
}

效果图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值