导读
1.网络操作基础知识
2.JSON基础常识
3.从服务器请求数据以及解析
网络操作基础知识
JSON基础常识
一个中括号表示一个集合,一个花括号表示一个对象
从服务器请求数据以及解析
JSON方法
配置文件 AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hala.view01">
<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>
<activity android:name=".DetailActivity"></activity>
</application>
<!--设置访问网络的权限,不要忘记-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
主页面布局文件 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="48dp"
android:text="Emilia Clarke"
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>
主页面java文件 MainActivity.java
package com.hala.view01;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
public void initView(){
findViewById(R.id.header).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,DetailActivity.class));
}
});
}
}
接收数据页面布局文件 activity_detail
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
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>
接收数据页面java文件 DetailActivity.java文件
package com.hala.view01;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import org.json.JSONArray;
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 AppCompatActivity {
private TextView name,author,content;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
essay e=(essay)msg.obj;
name.setText(e.getTitle());
author.setText(e.getAuthor());
content.setText(e.getContent());
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
initView();
initData();
}
public void initView(){
name=(TextView)findViewById(R.id.name);
author=(TextView)findViewById(R.id.author);
content=(TextView)findViewById(R.id.content);
}
public void initData() {
/*
HttpUrlConnection方案步骤
1。实例化一个Url的对象
2。获取HttpUrlConnection对象
3。设置请求链接属性(请求方法,响应时间)
4。获取响应码,判断是否连接成功
5。读取输入流并解析
*/
//注意要访问网络不能用原来的UI线程,而是要开辟新的线程
new Thread() {
@Override
public void run() {
try {
//第1步:参数是你要访问的接口
URL url = new URL("http://www.imooc.com/api/teacher?type=3&cid=1");
//第2步:openConnection是URLConnection类型的,通过向下造型实现
HttpURLConnection coon = (HttpURLConnection) url.openConnection();
//第3步:要用大写
coon.setRequestMethod("GET");
//这一步就是常见的响应超时
coon.setReadTimeout(6000);
//第4步:此方法在连接服务器的同时又从服务器获取了响应码
if (coon.getResponseCode() == 200) {
//第5步:len的作用是记录真实读到的数组长度
//baos是一个缓存流,保存所读取的数组
InputStream in = coon.getInputStream();
byte[] b = new byte[1024 * 512];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = in.read(b)) > -1) {
//参数1数组名
//参数2,3开始和结束下标
baos.write(b, 0, len);
}
String msg = baos.toString();
Log.e("TAG", msg);
//***JSON数据解析***
JSONObject obj=new JSONObject(msg);
//如果是一个数组就按以下语句处理
// JSONArray array=new JSONArray(msg);
int status=obj.getInt("status");
String msg2=obj.getString("msg");
Log.e("TAG",status+" "+msg2);
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);
//***将获得的数据布局到视图上***
/*
1。Handler是专门处理主线程与子线程关系的
2。Message是用来传递信息的
3。创建Handler对象如上第24行->obtainMessage获取Message对象->对于复杂类型自定义类essay并传值(其他类型也可以)
->通过.obj获取自定义类型到Message里->sendMessage传到上边第28行的方法handleMessage()
->获取对象或设置视图
*/
//因为数据请求重新开辟了一个子线程,而android4.0以后不允许通过子线程操作主线程
//所以这里要将控制权交给主线程
Message message=handler.obtainMessage();
essay e=new essay(title,author,content);
message.obj=e;
handler.sendMessage(message);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
}
}
自定义java文件 essay.java
package com.hala.view01;
/**
* Created by air on 2018/1/29.
*/
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;
}
}
显示结果
点击Emilia Clarke
GSON方法
Gson使用方法
⚠️这里很有可能输入gson回车后无信息,这是先输入com.google.code.gson:gson:2.8.0
如果还不行,在build.gradle(Module:app)文件里编写如下图标注行
配置文件 AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hala.view01">
<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>
<activity android:name=".DetailActivity"></activity>
</application>
<!--设置访问网络的权限,不要忘记-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
主页面布局文件 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="48dp"
android:text="Emilia Clarke"
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>
主页面java文件 MainActivity.java
package com.hala.view01;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends Activity {
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initDate();
}
public void initView(){
findViewById(R.id.header).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,DetailActivity.class));
}
});
}
public void initDate(){
new Thread(){
@Override
public void run() {
try {
URL url=new URL("http://www.imooc.com/api/teacher?type=2");
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(6000);
if(conn.getResponseCode()==200){
InputStream in=conn.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 result=baos.toString();
Log.e("TAG",result);
/*
这里如果用JSON处理方法,需要用JSONArray和JSONObject来一层层提取,工作量显而易见的大
而这是GSON就派上用场了,它可以便利化这一过程
*/
/*
GSON
1.解析普通的json对象(在Detail文件中演示)
2.解析json数组(此文件演示)
*/
//在Json格式里得到data类型的数据并交给字符串data
String data=new JSONObject(result).getString("data");
Gson gson=new Gson();
//参数1:满足json数组形式的字符串,是一个集合所以后边也要用集合接收
//参数2:要转化成什么对象,TypeToken需要指定范型,范型决定了最后转化的类型
//这里需要根据Json的类型建立相对应的实体类(这里是OutLine),实体类要和Json相匹配
//另外要注意这条语句的写法
ArrayList<OutLine> outline= gson.fromJson(data,new TypeToken<ArrayList<OutLine>>(){}.getType());
for(int i=0;i<outline.size();i++){
OutLine o=outline.get(i);
Log.e("TAG","id:"+o.getId()+" 标题:"+o.getName());
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
}
}
接收数据页面布局文件 activity_detail
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
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>
接收数据页面java文件 DetailActivity.java文件
package com.hala.view01;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.gson.Gson;
import org.json.JSONArray;
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 AppCompatActivity {
private TextView name,author,content;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
essay e=(essay)msg.obj;
name.setText(e.getTitle());
author.setText(e.getAuthor());
content.setText(e.getContent());
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
initView();
initData();
}
public void initView(){
name=(TextView)findViewById(R.id.name);
author=(TextView)findViewById(R.id.author);
content=(TextView)findViewById(R.id.content);
}
public void initData() {
/*
HttpUrlConnection方案步骤
1。实例化一个Url的对象
2。获取HttpUrlConnection对象
3。设置请求链接属性(请求方法,响应时间)
4。获取响应码,判断是否连接成功
5。读取输入流并解析
*/
//注意要访问网络不能用原来的UI线程,而是要开辟新的线程
new Thread() {
@Override
public void run() {
try {
//第1步:参数是你要访问的接口
URL url = new URL("http://www.imooc.com/api/teacher?type=3&cid=1");
//第2步:openConnection是URLConnection类型的,通过向下造型实现
HttpURLConnection coon = (HttpURLConnection) url.openConnection();
//第3步:要用大写
coon.setRequestMethod("GET");
//这一步就是常见的响应超时
coon.setReadTimeout(6000);
//第4步:此方法在连接服务器的同时又从服务器获取了响应码
if (coon.getResponseCode() == 200) {
//第5步:len的作用是记录真实读到的数组长度
//baos是一个缓存流,保存所读取的数组
InputStream in = coon.getInputStream();
byte[] b = new byte[1024 * 512];
int len = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = in.read(b)) > -1) {
//参数1数组名
//参数2,3开始和结束下标
baos.write(b, 0, len);
}
String msg = baos.toString();
Log.e("TAG", msg);
/*
解析普通的json对象
1.创建Gson对象
*/
JSONObject obj=new JSONObject(msg);
Gson gson=new Gson();
String data=obj.getString("data");
//参数1:一个满足json对象格式的字符串(注意json里的数据都可以转化为字符串)
//参数2:一个类的类对象,这里是自定义的,其返回值也是这个类对象类型
essay e=gson.fromJson(data,essay.class);
Message message=handler.obtainMessage();
message.obj=e;
handler.sendMessage(message);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
}
}
自定义java文件 essay.java
package com.hala.view01;
/**
* Created by air on 2018/1/29.
*/
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;
}
}
自定义文件 OutLine
package com.hala.view01;
/**
* Created by air on 2018/1/30.
*/
public class OutLine {
private int id;
private String name;
private String picSmall;
private String picBig;
private String description;
private String learner;
public OutLine(int id, String name, String picSmall, String picBig, String description, String learner) {
this.id = id;
this.name = name;
this.picSmall = picSmall;
this.picBig = picBig;
this.description = description;
this.learner = learner;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPicSmall() {
return picSmall;
}
public void setPicSmall(String picSmall) {
this.picSmall = picSmall;
}
public String getPicBig() {
return picBig;
}
public void setPicBig(String picBig) {
this.picBig = picBig;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLearner() {
return learner;
}
public void setLearner(String learner) {
this.learner = learner;
}
}
显示结果
点击Emilia Clarke