Android中的网络操作

Android中的网络操作

1.从服务器获取数据

Step 1 实例化一个URL对象
//构造URL对象
URL url = new URL("https://www.imooc.com/api/teacher?type=2&page=1");
Step 2 获取HttpURLConnection对象
/创建HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
Step 3 设置请求连接属性
//设置超时时间
connection.setConnectTimeout(30*1000);
//设置请求方法
connection.setRequestMethod("GET");
//设置请求属性:内容格式:json,数据集格式:utf-8  接收的字符集:utf-8
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("Charset","UTF-8");
connection.setRequestProperty("Accept-Charset","UTF-8");
//发起连接
connection.connect();
Step 4 获取响应码,判断连接结果码
//获取请求码
int responseCode = connection.getResponseCode();
//获取请求的消息
String responseMessage = connection.getResponseMessage();
if(responseCode == HttpURLConnection.HTTP_OK){

...
}
Step 5 读取输入流并解析【响应码判断成功后】
//获取数据
InputStream inputStream = connection.getInputStream();
//将数据转成字符串
result = streamToString(inputStream);
Step 6 开启新线程【敲黑板!】
           new Thread(new Runnable() {
               @Override
               public void run() {
             //将请求网络的操作移步到子线程
               ....
               }
           }).start();
Step 7 开启权限
<uses-permission android:name="android.permission.INTERNET" />

注意: 更新UI必须在主线程中,当点击按钮是要在子线程中请求网络;而你在请求网络的最后想将返回的数据放在TextView中为更新UI的操作,所以会报错。

此时需要从子线程回到主线程来进行更新UI的操作【也可用Handler】

//方式1
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        contextTxt.setText(result); 
    }
});
//方式2
contextTxt.post(new Runnable() {
    @Override
    public void run() {
      contextTxt.setText(result);
    }
});

解决Android 9.0以后对http请求的限制问题

  1. 创建安全配置文件

    ① 在res文件夹下创建xml/network-security-config文件

    ②增加cleartextTrafficPermitted属性

    <network-security-config>
        <base-config cleartextTrafficPermitted = "true" />
    </network-security-config>
    
  2. 添加安全配置文件

    AndroidManifest.xml中的Application声明

    android:networkSecurityConfig="@xml/network_security_config"
    

2.GET vs POST

1. Get&post比较

在这里插入图片描述

幂等性: 同样的一次操作,一次或多次的操作对系统的资源产生的影响是一样的。post每次都会向服务器提交数据,会产生修改所以post不是幂等性的。

get 获取数据 参数会在Url里面,采用明文的方式,从传输来看,不安全;但是,本质上来看,get方式不会修改服务器上的内容,是安全的。如获取朋友圈数据采用get

post 提交数据 参数不会直接放在Url里面,而是封装起来,从传输上来看,比较安全;而post方式是向服务器提交数据,会对服务器进行修改,相对而言,本质上没有get方式安全。如发一个朋友圈采用post

在这里插入图片描述

2.采用Post 方法请求网络
try {
    //构造URL对象type=2&page=1
    URL url = new URL("http://www.imooc.com/api/teacher");
    //创建HttpURLConnection
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    //设置超时时间
    connection.setConnectTimeout(30*1000);
    //设置请求方法
    connection.setRequestMethod("POST");
    //设置请求属性:内容格式:json,数据集格式:utf-8  接收的字符集:utf-8
    connection.setRequestProperty("Content-Type","application/json");
    connection.setRequestProperty("Charset","UTF-8");
    connection.setRequestProperty("Accept-Charset","UTF-8");

    //设置输入输出
    connection.setDoOutput(true);
    connection.setDoInput(true);
    //设置不能用缓存
    connection.setUseCaches(false);

    //发起连接
    connection.connect();
    //请求数据(名字中可能带有特殊字符,这是需要对其进行编码)
    String data = "username=" +getEncodeValue("imooc")+"&number=" +getEncodeValue("15099094403");

    OutputStream outputStream = connection.getOutputStream();
    //将封装好的所需要提交的数据写入outputStream
    outputStream.write(data.getBytes());
    outputStream.flush();
    outputStream.close();
    
    //获取请求码
    int responseCode = connection.getResponseCode();
    //获取请求的消息
    String responseMessage = connection.getResponseMessage();
    if(responseCode == HttpURLConnection.HTTP_OK){

        //获取数据
        InputStream inputStream = connection.getInputStream();
        //将数据转成字符串
        result = streamToString(inputStream);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                contextTxt.setText(result);
            }
        });
        

    }else{
        //TODO:ERROR FAIL
        Log.e(TAG, "run: error code:"+responseMessage+",message:"+responseMessage );
    }
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

3.解析数据

JSONObject json对象——{}括号

在这里插入图片描述

JSONArray json数组——[] 括号

在这里插入图片描述

Step 1 新建一个实体类LessonResult
package com.example.wanghui.networkactivity;

import java.util.List;

public class LessonResult {

    private int mStatus ;
    private List<Lesson> mLessons ;


    @Override
    public String toString() {
        return "LessonResult{" +
                "mStatus=" + mStatus +
                ", mLessons=" + mLessons +
                '}';
    }

    public int getmStatus() {
        return mStatus;
    }

    public void setmStatus(int mStatus) {
        this.mStatus = mStatus;
    }

    public List<Lesson> getmLessons() {
        return mLessons;
    }

    public void setmLessons(List<Lesson> mLessons) {
        this.mLessons = mLessons;
    }

    public static class Lesson{

        private int mID;
        private  String mName ;
        private  String mPicSmallUrl;
        private  String mPicBigUrl;
        private  String mDesctiption;
        private  int  mLearner;

        public int getmID() {
            return mID;
        }

        public void setmID(int mID) {
            this.mID = mID;
        }

        public String getmName() {
            return mName;
        }

        public void setmName(String mName) {
            this.mName = mName;
        }

        public String getmPicSmallUrl() {
            return mPicSmallUrl;
        }

        public void setmPicSmallUrl(String mPicSmallUrl) {
            this.mPicSmallUrl = mPicSmallUrl;
        }

        public String getmPicBigUrl() {
            return mPicBigUrl;
        }

        public void setmPicBigUrl(String mPicBigUrl) {
            this.mPicBigUrl = mPicBigUrl;
        }

        public String getmDesctiption() {
            return mDesctiption;
        }

        public void setmDesctiption(String mDesctiption) {
            this.mDesctiption = mDesctiption;
        }

        public int getmLearner() {
            return mLearner;
        }

        public void setmLearner(int mLearner) {
            this.mLearner = mLearner;
        }

        @Override
        public String toString() {
            return "Lesson{" +
                    "mID=" + mID +
                    ", mName='" + mName + '\'' +
                    ", mPicSmallUrl='" + mPicSmallUrl + '\'' +
                    ", mPicBigUrl='" + mPicBigUrl + '\'' +
                    ", mDesctiption='" + mDesctiption + '\'' +
                    ", mLearner=" + mLearner +
                    '}';
        }
    }
}
Step 2 创建JSON解析数据的方法handlerJSONData
private void handlerJSONData(String result) {

    try {
        //创建LessonResult
        LessonResult lessonResult = new LessonResult();
        List<LessonResult.Lesson> listLesson = new ArrayList<>();

        JSONObject jsonObject = new JSONObject(result);
        int status = jsonObject.getInt("status");

        //给LessonResult赋值status
        lessonResult.setmStatus(status);

        //获取JSONArray数组
        JSONArray lessons = jsonObject.getJSONArray("data");
        //获取data数组里面的数据
        if(lessons!=null && lessons.length()>0){
            for (int index = 0; index <lessons.length() ; index++) {
                JSONObject lesson = (JSONObject) lessons.get(index);

                //获取每一项数据
                int id = lesson.getInt("id");
                int learner = lesson.getInt("learner");
                String  name = lesson.getString("name");
                String  smallPic = lesson.getString("picSmall");
                String  bigPic = lesson.getString("picBig");
                String  description = lesson.getString("description");

                //创建LessonResult.Lesson 对象
                LessonResult.Lesson lessonItem = new LessonResult.Lesson();
                //赋值
                lessonItem.setmID(id);
                lessonItem.setmLearner(learner);
                lessonItem.setmName(name);
                lessonItem.setmPicSmallUrl(smallPic);
                lessonItem.setmPicBigUrl(bigPic);
                lessonItem.setmDesctiption(description);
                //将lessonItem添加到listLesson
                listLesson.add(lessonItem);
            }
            lessonResult.setmLessons(listLesson);
        }
        contextTxt.setText(lessonResult.toString());

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
测试结果

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值