1.创建一个安卓项目
把网络请求的架包导入
在build.gradle(Module.app)目录下
implementation 'com.squareup.okhttp:okhttp:2.7.5'
implementation 'com.alibaba:fastjson:1.2.68'
先创建xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="网络请求数据显示" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello World!"
android:textSize="20dp"
/>
</LinearLayout>
创建实体类
package com.hnjdzy.testjosn;
public class User {
private String sid;
private String tts;
private String content;
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getTts() {
return tts;
}
public void setTts(String tts) {
this.tts = tts;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
我们是一个网络请求一个网址,点击button按钮,获取网址中的content的信息,这个属性,其实除了content都可以不写
下面是网址的json数据
之后,就是写OKhttp的网络请求,之后解析数据,获取数据到文本框中
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
textView = findViewById(R.id.textView);
//设置button的点击事件
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
getHttp();
}
});
thread.start();
}
});
}
private void getHttp(){
OkHttpClient client = new OkHttpClient();
//默认是get请求,可以不用写
Request request = new Request.Builder()
.url("http://open.iciba.com/dsapi/?date=2019-05-03&file=json")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.i("失败信息", "onFailure: ");
}
@Override
public void onResponse(Response response) throws IOException {
//定义一个json去接收网络获取的字符串,之后解析
String json = response.body().string();
//[]parseArray,{}parseObject
User user = JSON.parseObject(json, User.class);
final String content = user.getContent();
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(content);
}
});
}
});
}
}
最后运行一下案例,获取了content里面的内容