为什么在托管 JSON 对象请求后会发生错误?

时间:2021-04-28 23:22:35

标签: java android json

我通过以下代码托管一个非常简单的 JSON 对象请求:

public class MainActivity extends AppCompatActivity {

    RequestQueue queue;
    String url = "https://www.google.com";
    String apiUrl = "https://jsonplaceholder.typicode.com/todos";
    String getApiUrl = "https://jsonplaceholder.typicode.com/todos/1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        queue = Volley.newRequestQueue(this);

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                getApiUrl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    Log.d("url", "onCreate: " + response.getString("title"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("url", "There was an error");
            }
        });
        queue.add(jsonObjectRequest);



    }

}

这段代码的重点是在这个 URL 的 JSON 对象中获取 title 属性:https://jsonplaceholder.typicode.com/todos/1

在我的 Manifest 中,我已经包含了对 Internet 的许可,并且在我的 build.gradle 中,包含了对 volley 的依赖。

Logcat 也没有显示任何致命错误。谢谢。

enter image description here

2 个答案:

答案 0 :(得分:0)

我检查了您的代码,它完全正常工作!!!而不是 Log.d() 使用 Log.e() 所以红色的数据对你来说会更明显:)

enter image description here

答案 1 :(得分:0)

更新:

我已经找到了解决问题的方法。问题是我的 build.gradle 中的最小 sdk 版本是 30,并且正在 30 编译,而我的模拟器的 API 级别是 29。

相关问题