布局 MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
MainActivity.java
package com.example.okhttpdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest =(Button)findViewById(R.id.send_request);
responseText=(TextView)findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v){
if(v.getId()==R.id.send_request){
sendRequestWithOkHttp();
}
}
private void sendRequestWithOkHttp(){
new Thread(new Runnable(){
@Override
public void run(){
try{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.baidu.com")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
showResponse(responseData);
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable(){
@Override
public void run(){
responseText.setText(response);
//responseText最初由TextView responseText;定义,代表TextView对象。
}
});
}
}
安卓 9 加强了保密性,导致无法进行非加密的 http 网络请求
解决方法:
在 AndroidManifest.xml 的 application 标签中新加:
android:usesCleartextTraffic="true"
运行一下,如下图所示:
获取json数据
只需要把这行代码
Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
改成这样
Request request = new Request.Builder()
.url("http://10.0.2.2:8080/Demo22/get_data.json")
//测试 url 地址 http://10.0.2.2:8080/Demo22/get_data.json
.build();
运行一下,如下图所示:
使用 GSON 解析JSON数据
先添加依赖
implementation 'com.google.code.gson:gson:2.7'
再新建一个 App 类,写一个 javabean
package com.example.okhttpdemo;
public class App {
private String id;
private String name;
private String version;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
接着在下面重新写一个 parseJSONWithGSON 方法:
private void parseJSONWithGSON(final String jsonData){
Gson gson =new Gson();
List<App> appList = gson.fromJson(jsonData,new TypeToken<List<App>>()
{}.getType());
runOnUiThread(new Runnable(){
@Override
public void run(){
//responseText.setText(response);
for(App app:appList){
responseText.append("id is "+app.getId()+"\n");
responseText.append("name is "+app.getName()+"\n");
responseText.append("version is "+app.getVersion()+"\n");
}
}
});
}
运行一下,如下图所示: