安卓开发,使用okhttp读取网页内容,为什么我一调用这个函数就闪退呢?
okhttp版本3.8.1
btn.setOnClickListener(new View.OnClickListener() {
private void sendRequestWithOkHttp(){
new Thread(new Runnable() {
@Override
public void run() {
try{
OkHttpClient client = new OkHttpClient();
Request request=new Request.Builder()
.url("https://632a6f811090510116c05b32.mockapi.io/timelist")
.build();
Response response= client.newCall(request).execute();
String responseData =response.body().string();
parseJSONWithJSONObject(responseData);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
private void parseJSONWithJSONObject(String jsonData){
try{
JSONArray jsonArray=new JSONArray(jsonData);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
String currenttime=jsonObject.getString("current_time");
Toast.makeText(MainActivity.this,"获取JSON成功!"+currenttime,Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
sendRequestWithOkHttp();
}
});