Как вы используете Android Volley API?

Я собираюсь внедрить библиотеку Android Volley в своих следующих проектах (презентация Google IO о Volley).

Однако я не нашел никакого серьезного API для этой библиотеки.

Как загрузить файлы, выполнить POST/GET-запросы и добавить парсер Gson в качестве парсера JSON с помощью Volley?

Исходный код

Ответ 1

Изменить:, наконец, официальное обучение о библиотеке Volley

Я нашел несколько примеров о библиотеке Volley

Надеюсь, это поможет вам

Ответ 2

К сожалению, до сих пор нет документации для библиотеки Volley, такой как JavaDocs. Только репо на github и несколько учебных пособий через Интернет. Поэтому единственными хорошими документами являются исходный код:). Когда я играл с Volley, я прочитал этот учебник.

О сообщении/получении вы можете прочитать это: Volley - параметры POST/GET

Надеюсь, что это поможет

Ответ 3

Это иллюстрация для создания запроса POST с помощью Volley. StringRequest используется для получения ответа в виде строки.
Предполагая, что ваш rest API возвращает JSON. Ответ JSON от вашего API получен здесь как String, который вы можете снова скрывать в JSON и обрабатывать его дальше. Добавлены комментарии в код.

StringRequest postRequest = new StringRequest(Request.Method.POST, "PUT_YOUR_REST_API_URL_HERE",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        // Process your json here as required
                    } catch (JSONException e) {
                        // Handle json exception as needed
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    String json = null;
                    NetworkResponse response = error.networkResponse;
                    if(response != null && response.data != null){
                        switch(response.statusCode) {
                            default:
                                String value = null;
                                try {
                                    // It is important to put UTF-8 to receive proper data else you will get byte[] parsing error.
                                    value = new String(response.data, "UTF-8");
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                                json = trimMessage(value, "message");
                                // Use it for displaying error message to user 
                                break;
                        }
                    }
                    loginError(json);
                    progressDialog.dismiss();
                    error.printStackTrace();
                }  
                public String trimMessage(String json, String key){
                    String trimmedString = null;
                    try{
                        JSONObject obj = new JSONObject(json);
                        trimmedString = obj.getString(key);
                    } catch(JSONException e){
                        e.printStackTrace();
                        return null;
                    }
                    return trimmedString;
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("abc", "pass abc");
            params.put("xyz", "pass xyz");
            // Pass more params as needed in your rest API
    // Example you may want to pass user input from EditText as a parameter
    // editText.getText().toString().trim()
            return params;
        }  
        @Override
        public String getBodyContentType() {
            // This is where you specify the content type
            return "application/x-www-form-urlencoded; charset=UTF-8";
        }
    };

    // This adds the request to the request queue
    MySingleton.getInstance(YourActivity.this)
.addToRequestQueue(postRequest);

//Ниже представлен класс MySingleton

public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private static Context mCtx;  
    private MySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();
    }

    public static synchronized MySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }
}

Ответ 4

Просто добавьте библиотеку volley.jar в свой проект. и затем

В соответствии с документацией на Android:

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // process your response here

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        //perform operation here after getting error
    }            
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

Для получения дополнительной справки обратитесь Как пользователь Volley

Ответ 5

Используйте этот класс. Он предоставляет вам простой способ подключения к базе данных.

public class WebRequest {

    private Context mContext;
    private String mUrl;
    private int mMethod;
    private VolleyListener mVolleyListener;

    public WebRequest(Context context) {
        mContext = context;
    }

    public WebRequest setURL(String url) {
        mUrl = url;
        return this;
    }

    public WebRequest setMethod(int method) {
        mMethod = method;
        return this;
    }

    public WebRequest readFromURL() {
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);
        StringRequest stringRequest = new StringRequest(mMethod, mUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                mVolleyListener.onRecieve(s);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mVolleyListener.onFail(volleyError);
            }
        });

        requestQueue.add(stringRequest);
        return this;
    }

    public WebRequest onListener(VolleyListener volleyListener) {
        mVolleyListener = volleyListener;
        return this;
    }

    public interface VolleyListener {
        public void onRecieve(String data);

        public void onFail(VolleyError volleyError);
    }
}

Пример использования:

new WebRequest(mContext)
     .setURL("http://google.com")
     .setMethod(Request.Method.POST)
     .readFromURL()
     .onListener(new WebRequest.VolleyListener() {
         @Override
         public void onRecieve(String data) {
         }

         @Override
         public void onFail(VolleyError volleyError) {
         }
     });

Ответ 6

Простым способом

 private void load() {
    JsonArrayRequest arrayreq = new JsonArrayRequest(ip.ip+"loadcollege.php",
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {

                    Album a;

                    try {
                        JSONArray data = new JSONArray(response.toString());
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject c = data.getJSONObject(i);
                            one = c.getString("cname").split(",");
                            two=c.getString("caddress").split(",");
                            three = c.getString("image").split(",");
                            four = c.getString("cid").split(",");
                            five = c.getString("logo").split(",");




                            a = new Album(one[0].toString(),two[0].toString(),ip.ip+"images/"+ three[0].toString(),four[0].toString(),ip.ip+"images/"+ five[0].toString());
                            albumList.add(a);

                        }
                        adapter.notifyDataSetChanged();


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            // The final parameter overrides the method onErrorResponse() and passes VolleyError
            //as a parameter
            new Response.ErrorListener() {
                @Override
                // Handles errors that occur due to Volley
                public void onErrorResponse(VolleyError error) {
                    Log.e("Volley", "Error");
                }
            }
    );
    // Adds the JSON array request "arrayreq" to the request queue
    requestQueue.add(arrayreq);
}

Ответ 7

Перед тестированием всех вышеперечисленных ответов включите

compile 'com.android.volley:volley:1.0.0'

в вашем файле градиента и не забудьте добавить разрешение Интернета в файл манифеста.