MainActivity
package com.example.myapplication;
import androidx.appcompat.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.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
TextView textView;
TextView textViewAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textViewAge = findViewById(R.id.textView2);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("http://148.70.46.9/object3");
//URL url = new URL("http://148.70.46.9/usercenter");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
//
InputStream inputStream = urlConnection.getInputStream();// 字节流
Reader reader = new InputStreamReader(inputStream);//字符流
BufferedReader bufferedReader = new BufferedReader(reader);// 缓存流
String result = "";
String temp;
while ((temp = bufferedReader.readLine()) != null) {
result += temp;
}
Thread.sleep(2000);
String finalresult = result;
runOnUiThread(new Runnable() {
@Override
public void run() {
//textView.setText(finalresult);
try {
JSONObject jsonObject = new JSONObject(finalresult);
String classname = jsonObject.getString("classname");
textView.setText(classname);
//int age =jsonObject.getInt("age");
//JSonObject jsonObject1 = jsonObject.getJSonObject("class");
//String classname1 = jsonObject1.getString("classname");
JSONArray jsonArray = jsonObject.getJSONArray("students");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonArrayJSONObject = jsonArray.getJSONObject(i);
String name = jsonArrayJSONObject.getString("name");
Log.i("MainActivity", name);
textViewAge.setText(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Log.i("MainActivity", result);
inputStream.close();
reader.close();
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
activity_main.xml



