Android development to get back-end data

First set the following lines in AndroidManifest.xml

<!-- 允许用户访问网络,这一行要加在<manifest>的下一行 -->
<uses-permission android:name="android.permission.INTERNET" />
<!--这一行也是需要的,否则会报错,我的是这样,这行加在<application>标签内-->
android:usesCleartextTraffic="true"

Then the java part

//post方式
//body传值
try {
    
    
	//要发送的json数据
	String json = "{}";
	//创建http客户端
    OkHttpClient client = new OkHttpClient();
    //创建http请求
    Request request = new Request.Builder()
    .url("http://localhost:9000/user/mine")
    .post(RequestBody.create(MediaType.parse("application/json"), json))
    .build();
    //执行发送的指令
    Response response = client.newCall(request).execute();
    //获取后端数据
    String res = response.body().string();
    //因为只有一条数据所以直接转换为对象
    JSONObject resData = new JSONObject(res);
    //在安卓studio控制台打印输出
    Log.d("code", "" + resData.getInt("code"));
    //如果又多条数据则需要做这一步处理,首先把获得的数据存进数组
    JSONArray jsonArray = new JSONArray(resData);
    //遍历数组,把每一条数组内容转换成json对象并打印输出
    for (int i =0;i<jsonArray.length();i++) {
    
    
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    Log.d("code",""+jsonObject.getInt("id"));
    }
}

The value of params is similar, only the differences are listed below

//创建这两个东西,这是你url后面要传的参数
FormBody.Builder params = new FormBody.Builder();
params.add("", "");
//创建请求
Request request = new Request.Builder()
.url("http://112.124.7.23:9000/user/mine")
.post(params.build())
.build();

The other code is the same, this is the post method to get the request

Guess you like

Origin blog.csdn.net/qq_43511063/article/details/109408207