Android:获取JSON响应
创始人
2024-10-13 12:31:10
0

要获取JSON响应,可以使用Android提供的Volley库或者使用Java的HttpURLConnection类。以下是两种解决方法的示例代码:

使用Volley库:

  1. 首先,确保在你的项目中添加了Volley库的依赖。在build.gradle文件中添加以下代码:
dependencies {
    implementation 'com.android.volley:volley:1.2.0'
}
  1. 创建一个请求队列和一个方法来获取JSON响应:
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;

public class MainActivity extends AppCompatActivity {

    private RequestQueue requestQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化请求队列
        requestQueue = Volley.newRequestQueue(this);

        // 发起获取JSON响应的请求
        getJsonResponse();
    }

    private void getJsonResponse() {
        String url = "https://api.example.com/data.json";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        // 处理JSON响应
                        try {
                            // 从JSON对象中获取数据
                            String data = response.getString("data");
                            
                            // 处理数据...
                            
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // 处理错误响应
                        error.printStackTrace();
                    }
                });

        // 将请求添加到请求队列中
        requestQueue.add(request);
    }
}

使用HttpURLConnection类:

  1. 在AndroidManifest.xml文件中添加Internet权限:

  1. 创建一个异步任务来获取JSON响应:
import android.os.AsyncTask;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 发起获取JSON响应的请求
        new GetJsonResponseTask().execute();
    }

    private class GetJsonResponseTask extends AsyncTask {

        @Override
        protected JSONObject doInBackground(Void... voids) {
            String url = "https://api.example.com/data.json";
            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try {
                // 创建URL对象
                URL apiUrl = new URL(url);

                // 打开连接
                connection = (HttpURLConnection) apiUrl.openConnection();
                connection.setRequestMethod("GET");

                // 获取输入流
                InputStream inputStream = connection.getInputStream();

                // 创建BufferedReader对象来读取输入流
                reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                String line;

                // 读取输入流并将其存储在StringBuilder中
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }

                // 将JSON字符串转换为JSONObject
                return new JSONObject(stringBuilder.toString());

            } catch (IOException | JSONException e) {
                e.printStackTrace();
            } finally {
                // 关闭连接和BufferedReader
                if (connection != null) {
                    connection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(JSONObject response) {
            if (response != null) {
                // 处理JSON响应
                try {
                    // 从JSON对象中获取数据
                    String data = response.getString("data");

                    // 处理数据...

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                // 处理错误响应
            }
        }
    }
}

这些代码示例可以用来获取JSON响应,并在获取到响应后进行相应的处理。

相关内容

热门资讯

一分钟揭秘!pokermast... 一分钟揭秘!pokermaster脚本,大菠萝免费辅助器,AI教程(有挂教程);玩家必备必赢加哟《1...
科技揭秘!aapoker透视脚... 1、科技揭秘!aapoker透视脚本入口,pokerrrr2辅助,系统教程(有挂技巧);详细教程。2...
热点讨论!pokemmo脚本辅... 热点讨论!pokemmo脚本辅助下载,hhpoker怎么开透视,透牌教程(有挂方法);人气非常高,a...
专业讨论!wepoker破解是... 1、专业讨论!wepoker破解是真的还是假的,hhpoker破解工具,安装教程(有挂透明)。2、w...
一分钟教你!pokemmo手机... 一分钟教你!pokemmo手机辅助软件,hhpoker有没有辅助,2025新版技巧(有挂教程)1、很...
科技分享!uupoker有透视... 科技分享!uupoker有透视吗,wepoker模拟器哪个,安装教程(有挂透视);《WPK辅助透视》...
推荐一款!德普之星辅助工具如何... 推荐一款!德普之星辅助工具如何打开,pokemmo脚本最新版,2025版教程(有挂透明)是一款可以让...
我来教大家!wepoker怎么... 《我来教大家!wepoker怎么发冤家牌,wepoker私局代打,第三方教程(有挂辅助)》 wepo...
分享一款!购买wepoker模... 分享一款!购买wepoker模拟器,aapoker怎么选牌,wpk教程(有挂技巧);1.购买wepo...
重大推荐!拱趴大菠萝作弊方法,... 《重大推荐!拱趴大菠萝作弊方法,拱趴大菠萝万能辅助器,切实教程(有挂攻略)》 拱趴大菠萝万能辅助器软...