添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
导入 OkHttp3 依赖库
在 Module 下的 build.gradle 配置文件中的 dependencies 节点 , 进行如下配置 ;
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
非https报错的的处理办法
CLEARTEXT communication to 121.4.99.98 not permitted by network security policy
在AndroidManifest.xml application 添加 android:usesCleartextTraffic="true"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context=".MainActivity"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="获取数据"
android:layout_width="match_parent"
android:layout_height="60dp"
android:id="@+id/getData" />
<TextView
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="500dp"
android:background="#456789"/>
</LinearLayout>
package com.example.wsd;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.getData);
content = findViewById(R.id.content);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//第一步获取okHttpClient对象
OkHttpClient client = new OkHttpClient.Builder()
.build();
//第二步构建Request对象
Request request = new Request.Builder()
.url("http://121.4.99.98:5000?num=30")
.get()
.build();
//第三步构建Call对象
Call call = client.newCall(request);
//第四步:异步get请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("onFailure", e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string(); // [[7654,"21.80","94.00","2022-11-19 19:21:54"],[7653,"21.70","94.00","2022-11-19 19:21:44"]]
content.setText(result);
}
});
}
});
}
}