繁体   English   中英

使用Okhttp和GSON库解析JSON响应时,我在主线程异常中获取网络

[英]When parse a JSON response using Okhttp and GSON Library then i am getting Network on main thread exception

我在我的项目gradle文件中给出了相关性,如下所示。

编译'com.google.code.gson:gson:2.4'

编译'com.squareup.okhttp3:okhttp:3.1.2'

我收到异常android.os.NetwokOnMainThreadException

我无法获得该如何解决该问题的方法,因为我每天都要查看下面链接中给出的OKHTTP食谱表格。 https://github.com/square/okhttp/wiki/食谱

    public class MainActivity extends AppCompatActivity {

    private final OkHttpClient client = new OkHttpClient();
    private final Gson gson = new Gson();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            Request request = new Request.Builder()
                    .url("https://api.github.com/gists/c2a7c39532239ff261be")
                    .build();
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful())
                Toast.makeText(getApplicationContext(),"false",Toast.LENGTH_LONG).show();

            Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
            for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
                Toast.makeText(getApplicationContext(),entry.getKey().toString(),Toast.LENGTH_LONG).show();
            }
        }catch (Exception e){
            Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
        }
    }

    static class Gist {
        Map<String, GistFile> files;
    }

    static class GistFile {
        String content;
    }

}

使用enqueue()而不是execute()

Execute在同一线程(在本例中为UI线程)上运行它。

Enqueue在后台线程上运行它。

您想在后台线程上而不是在UI线程上调用网络操作。

请在此处查看“ Call界面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM