我通过以下代码托管一个非常简单的 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 也没有显示任何致命错误。谢谢。