【问题标题】:I'm trying fetch data from an api but it seems to be not working我正在尝试从 api 获取数据,但它似乎无法正常工作
【发布时间】:2018-09-05 07:21:19
【问题描述】:
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(this, "hi This is a test", Toast.LENGTH_SHORT).show();

        String URL = "i have given a valid API, since its company's api i cant share";

        RequestQueue requestQueue = Volley.newRequestQueue(this);

        JsonObjectRequest objectRequest = new JsonObjectRequest(
                Request.Method.GET,
                URL,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.e("response", response.toString());
                        Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, "this is error", Toast.LENGTH_SHORT).show();
                        Log.e("error", error.toString());
                    }
                }
        );
        requestQueue.add(objectRequest);
    }
}

我正在尝试从 api 获取数据,但它似乎无法正常工作。 两个 toast 都没有被执行(响应,错误)。 我已经包含了所有依赖项并包含了 Internet 权限。 请帮忙

【问题讨论】:

  • “它似乎不起作用”。这是非常模糊的。 “响应,错误”,这也可能更具体。您能否更新您的问题以包含所有相关信息?
  • 你在 logcat 中得到什么了吗?
  • 从 api 获得响应需要时间。请检查您的 logcat。
  • Volley 参考这里My GitHub Repository
  • logcat 没什么可显示的

标签: java android api android-volley


【解决方案1】:

将 Request.Method.GET 更改为 Request.Method.POST 并尝试可能会解决...

如果这不起作用,那么试试这个... 使用 StringRequest 代替 JsonObjectRequest

使用 StringRequest 你需要这个改变

StringRequest stringRequest = new StringRequest (
            Request.Method.GET,
            URL,

            new Response.Listener<String>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.e("response", response.toString());
                    Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this, "this is error", Toast.LENGTH_SHORT).show();
                    Log.e("error", error.toString());
                }
            }
    );
    requestQueue.add(stringRequest);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 2013-12-14
    • 2017-09-04
    相关资源
    最近更新 更多