我正在尝试从api获取数据,但似乎无法正常工作

时间:2018-09-05 07:21:20

标签: java android api android-volley

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获取数据,但似乎无法正常工作。 吐司都没有执行(响应,错误)。 我已经包括了所有依赖关系,也包括了互联网许可。 请帮助

1 个答案:

答案 0 :(得分:0)

将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);