Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

How to send a GET request ( with parameters ) with GSON+Volley to a server

hi,

Can anyone show me an example of using GSON+Volley to send a GET request with some parameters to a server?

Below are 2x files that is currently in a project package using Volley and GSON and GET/POST:


GsonGetRequest.java

package example.api;

import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException;

import java.io.UnsupportedEncodingException; import java.lang.reflect.Type;

public class GsonGetRequest<T> extends Request<T> { private final Gson gson; private final Type type; private final Response.Listener<T> listener;

/**
 * Make a GET request and return a parsed object from JSON.
 *
 * @param url URL of the request to make
 * @param type is the type of the object to be returned
 * @param listener is the listener for the right answer
 * @param errorListener  is the listener for the wrong answer
 */
public GsonGetRequest
(String url, Type type, Gson gson,
 Response.Listener<T> listener, Response.ErrorListener errorListener)
{
    super(Method.GET, url, errorListener);

    this.gson = gson;
    this.type = type;
    this.listener = listener;
}

@Override
protected void deliverResponse(T response)
{
    listener.onResponse(response);
}

@Override
protected Response<T> parseNetworkResponse(NetworkResponse response)
{
    try
    {
        String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));

        return (Response<T>) Response.success
                (
                        gson.fromJson(json, type),
                        HttpHeaderParser.parseCacheHeaders(response)
                );
    }
    catch (UnsupportedEncodingException e)
    {
        return Response.error(new ParseError(e));
    }
    catch (JsonSyntaxException e)
    {
        return Response.error(new ParseError(e));
    }
}

}


ApiRequest.java

package example.api;

import com.android.volley.Response; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody;

import java.io.IOException; import java.util.ArrayList;

import officialfoodcrush_foo.foodcrushproject.model.DummyObject; import officialfoodcrush_foo.foodcrushproject.model.DummyObjectDeserializer; import officialfoodcrush_foo.foodcrushproject.model.FeedObject; import officialfoodcrush_foo.foodcrushproject.model.FeedObjectDeserializer; import officialfoodcrush_foo.foodcrushproject.model.SearchObject;

public class ApiRequest { /** * Returns a dummy object * * @param listener is the listener for the correct answer * @param errorListener is the listener for the error response * * @return @return {@link } */ public static GsonGetRequest<DummyObject> getDummyObject ( Response.Listener<DummyObject> listener, Response.ErrorListener errorListener ) { final String url = "http://www.mocky.io/v2/55973508b0e9e4a71a02f05f";

    final Gson gson = new GsonBuilder()
            .registerTypeAdapter(DummyObject.class, new DummyObjectDeserializer())
            .create();

    return new GsonGetRequest<>
            (
                    url,
                    new TypeToken<DummyObject>() {}.getType(),
                    gson,
                    listener,
                    errorListener
            );
}

/**
 * Returns a dummy object's array
 *
 * @param listener is the listener for the correct answer
 * @param errorListener is the listener for the error response
 *
 * @return {@link }
 */
public static GsonGetRequest<ArrayList<FeedObject>> getFeedObjectArray
(
        Response.Listener<ArrayList<FeedObject>> listener,
        Response.ErrorListener errorListener
)
{

// final String url = "http://unilowstudio.com/dummy/"; final String url = "http://unilowstudio.com/dummy/test.json"; // final String url = "http://api.androidhive.info/json/movies.json";

    final Gson gson = new GsonBuilder()
            .registerTypeAdapter(FeedObject.class, new FeedObjectDeserializer())
            .create();

    return new GsonGetRequest<>
            (
                    url,
                    new TypeToken<ArrayList<FeedObject>>() {}.getType(),
                    gson,
                    listener,
                    errorListener
            );
}


/**
 * An example call (not used in this example app) to demonstrate how to do a Volley POST call
 * and parse the response with Gson.
 *
 * @param listener is the listener for the success response
 * @param errorListener is the listener for the error response
 *
 * @return {@link }
 */
public static GsonPostRequest getDummyObjectArrayWithPost
(
        Response.Listener<DummyObject> listener,
        Response.ErrorListener errorListener
)
{
    final String url = "http://PostApiEndpoint";
    final Gson gson = new GsonBuilder()
            .registerTypeAdapter(DummyObject.class, new DummyObjectDeserializer())
            .create();

    final JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("name", "Ficus");
    jsonObject.addProperty("surname", "Kirkpatrick");

    final JsonArray squareGuys = new JsonArray();
    final JsonObject dev1 = new JsonObject();
    final JsonObject dev2 = new JsonObject();
    dev1.addProperty("name", "Jake Wharton");
    dev2.addProperty("name", "Jesse Wilson");
    squareGuys.add(dev1);
    squareGuys.add(dev2);

    jsonObject.add("squareGuys", squareGuys);

    final GsonPostRequest gsonPostRequest = new GsonPostRequest<>
            (
                    url,
                    jsonObject.toString(),
                    new TypeToken<DummyObject>()
                    {
                    }.getType(),
                    gson,
                    listener,
                    errorListener
            );

    gsonPostRequest.setShouldCache(false);

    return gsonPostRequest;
}

}