安卓开发,使用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();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();
}
});
看下异常报告,然后可以学着debug一下看看报错前的异常情况
1、返回的JSON格式并不是JSONArray,可以改成JSONObject。
JSONObject jsonObject = new JSONObject(jsonData);
String currenttime=jsonObject.getString("current_time");
Log.d("jsonData::",currenttime);
2、如果在一个线程中没有调用Looper.prepare(),就不能在该线程中创建Toast。可以这样:
public class ToastUtils {
static Toast toast = null;
public static void show(Context context, String text) {
try {
if(toast!=null){
toast.setText(text);
}else{
toast= Toast.makeText(context, text, Toast.LENGTH_SHORT);
}
toast.show();
} catch (Exception e) {
//解决在子线程中调用Toast的异常情况处理
Looper.prepare();
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
Looper.loop();
}
}
}
可以贴下异常,方便定位问题