我已经在我的项目 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/Recipes
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;
}
}