Make an HTTP request with android

后端 未结 12 1132
时光取名叫无心
时光取名叫无心 2020-11-21 06:38

I have searched everywhere but I couldn\'t find my answer, is there a way to make a simple HTTP request? I want to request a PHP page / script on one of my websites but I do

12条回答
  •  春和景丽
    2020-11-21 07:08

    The most simple way is using the Android lib called Volley

    Volley offers the following benefits:

    Automatic scheduling of network requests. Multiple concurrent network connections. Transparent disk and memory response caching with standard HTTP cache coherence. Support for request prioritization. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel. Ease of customization, for example, for retry and backoff. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network. Debugging and tracing tools.

    You can send a http/https request as simple as this:

            // Instantiate the RequestQueue.
            RequestQueue queue = Volley.newRequestQueue(this);
            String url ="http://www.yourapi.com";
            JsonObjectRequest request = new JsonObjectRequest(url, null,
                new Response.Listener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (null != response) {
                             try {
                                 //handle your response
                             } catch (JSONException e) {
                                 e.printStackTrace();
                             }
                        }
                    }
                }, new Response.ErrorListener() {
    
                @Override
                public void onErrorResponse(VolleyError error) {
    
                }
            });
            queue.add(request);
    

    In this case, you needn't consider "running in the background" or "using cache" yourself as all of these has already been done by Volley.

提交回复
热议问题