6.9

所花时间(包括上课):2

打码量(行):200

博客量(篇):1

了解到知识点:学习volley

 

package com.example.myapp;

 

import android.os.Bundle;

import android.util.Log;

 

import androidx.appcompat.app.AppCompatActivity;

 

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.Response;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.JsonObjectRequest;

import com.android.volley.toolbox.Volley;

 

import org.json.JSONObject;

 

public class MainActivity extends AppCompatActivity {

 

    private static final String TAG = "MainActivity";

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        // 示例代码:发送 GET 请求

        sendGetRequest();

    }

 

    private void sendGetRequest() {

        // 创建一个请求队列

        RequestQueue queue = Volley.newRequestQueue(this);

        String url = "http://api.example.com/data_endpoint";

 

        // 创建一个 JSON 请求

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(

                Request.Method.GET, url, null,

                new Response.Listener<JSONObject>() {

                    @Override

                    public void onResponse(JSONObject response) {

                        // 处理成功响应

                        Log.d(TAG, "Response: " + response.toString());

                    }

                },

                new Response.ErrorListener() {

                    @Override

                    public void onErrorResponse(VolleyError error) {

                        // 处理请求错误

                        Log.e(TAG, "Error: " + error.getMessage());

                    }

                });

 

        // 将请求添加到队列中

        queue.add(jsonObjectRequest);

    }

}

posted @ 2024-06-09 16:04  赵千万  阅读(2)  评论(0编辑  收藏  举报