xristos milios
xristos milios

Reputation: 3

How can i make an HTTP POST request and and use the Json Response i should get in android

I try to make an http login request to a web service. I set the JSONobject request as it follows but when i try to debug the code, response JSON object appears to be null. (I should get as response a JSON object). Any idea?

 public UserData initLogin(Creds cr) {

    StringBuilder finalURL = new StringBuilder("https://");
    finalURL.append(credentials.getUrl());
    finalURL.append("/s1services");

    Response.Listener<JSONObject> r1 = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            res = response.toString();
            us = gson.fromJson(String.valueOf(response), UserData.class);

        }
    };
    JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, finalURL.toString(), cr.serObj(), r1, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });






    return us;
}

should I put this request to a request queue or something? I should mention that credentials class has a URL attribute and a getUrl() method.

Upvotes: 0

Views: 60

Answers (1)

Mathias
Mathias

Reputation: 1106

I would follow the example in the Android doc:

StringBuilder finalURL = new StringBuilder("https://");
finalURL.append(credentials.getUrl());
finalURL.append("/s1services");
String url = finalURL.toString();

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
    (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {
        //handle your json response here
        us = gson.fromJson(String.valueOf(response), UserData.class);
    }
  }, new Response.ErrorListener() {

  @Override
  public void onErrorResponse(VolleyError error) {
      // TODO: Handle error

  }
});

// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);

See: https://developer.android.com/training/volley/request

Upvotes: 0

Related Questions