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请求的限制问题
-
创建安全配置文件
① 在res文件夹下创建xml/network-security-config文件
②增加cleartextTrafficPermitted属性
<network-security-config> <base-config cleartextTrafficPermitted = "true" /> </network-security-config>
-
添加安全配置文件
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();
}
}