Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • how to access restful webservice using volley library

    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 1.24k
    Answer it

    I have created a restful web service using this tutorial http://www.tutecentral.com/restful-api-for-android-part-1/ after running this i got an auto generated java file which contains the following code

    public class RestAPI {
    
      private final String urlString = "http://10.0.2.2:58893/Handler1.ashx"; 
      private static String convertStreamToUTF8String(InputStream stream) throws IOException {
        String result = "";
        StringBuilder sb = new StringBuilder();
        try {
            InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
            char[] buffer = new char[4096];
            int readedChars = 0;
            while (readedChars != -1) {
                readedChars = reader.read(buffer);
                if (readedChars > 0)
                   sb.append(buffer, 0, readedChars);
            }
            result = sb.toString();
        } catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }//
        return result;
    }
    private String load(String contents) throws IOException {
        URL url = new URL(urlString);
        Log.e("load r1","load r1");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(60000);
        Log.e("load r2","load r2");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        Log.e("load r3","load r3");
        OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
        w.write(contents);
        w.flush();
        Log.e("load r4","load r4");
        InputStream istream = conn.getInputStream();
        Log.e("load r5","load r5");
        String result = convertStreamToUTF8String(istream);
        return result;
    }
    
    private Object mapObject(Object o) {
        Object finalValue = null;
        if (o.getClass() == String.class) {
            finalValue = o;
        }
        else if (Number.class.isInstance(o)) {
            finalValue = String.valueOf(o);
        } else if (Date.class.isInstance(o)) {
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
            finalValue = sdf.format((Date)o);
        }
        else if (Collection.class.isInstance(o)) {
            Collection<?> col = (Collection<?>) o;
            JSONArray jarray = new JSONArray();
            for (Object item : col) {
                jarray.put(mapObject(item));
            }
            finalValue = jarray;
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            Method[] methods = o.getClass().getMethods();
            for (Method method : methods) {
                if (method.getDeclaringClass() == o.getClass()
                        && method.getModifiers() == Modifier.PUBLIC
                        && method.getName().startsWith("get")) {
                    String key = method.getName().substring(3);
                    try {
                        Object obj = method.invoke(o, null);
                        Object value = mapObject(obj);
                        map.put(key, value);
                        finalValue = new JSONObject(map);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
    
        }
        return finalValue;
    }
    
    public JSONObject GetDoctors(String Terr&#95;Code) throws Exception {
        JSONObject result = null;
        JSONObject o = new JSONObject();
        JSONObject p = new JSONObject();
        o.put("interface","RestAPI");
        o.put("method", "GetDoctors");
        p.put("Terr&#95;Code",mapObject(Terr&#95;Code));
        o.put("parameters", p);
        String s = o.toString();
        String r = load(s);
        result = new JSONObject(r);
        return result;
    }
    
    public JSONObject GetUserDetail(String IMEINO) throws Exception {
        JSONObject result = null;
        JSONObject o = new JSONObject();
        JSONObject p = new JSONObject();
        o.put("interface","RestAPI");
        o.put("method", "GetUserDetail");
        p.put("IMEINO",mapObject(IMEINO));
        o.put("parameters", p);
        String s = o.toString();
        String r = load(s);
        result = new JSONObject(r);
        return result;
    }
    
    
    public JSONObject GetProductsForOrders(String ff&#95;code) throws Exception {
        JSONObject result = null;
        JSONObject o = new JSONObject();
        JSONObject p = new JSONObject();
        o.put("interface","RestAPI");
        o.put("method", "GetProductsForOrders");
        p.put("ff&#95;code",mapObject(ff&#95;code));
        o.put("parameters", p);
        String s = o.toString();
        String r = load(s);
        result = new JSONObject(r);
        return result;
    }
    

    }

    I want to access the these method using volley as async task is very slow, but i don't understand how to call methods in volley code. I've tried in the below code but i get the error of "bad url null"

           public void requestJSON() {
              // Tag used to cancel the request
              String tag&#95;json&#95;obj = "json&#95;obj&#95;req";
    
              final ProgressDialog pDialog = new ProgressDialog(context);
              pDialog.setMessage("Loading...");
              pDialog.show();
              JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, null,
                    null, new Response.Listener<JSONObject>() {
    
                       @Override
                       public void onResponse(JSONObject response) {
    
                            RestAPI restAPI = new RestAPI();
                            try {
                                  response = restAPI.GetDoctors(terrcode);                           
                            } 
    
                            catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
    
                     display.setText(response.toString());
                           Log.e("json data",response.toString());
                          pDialog.hide();
                       }
    
    
    
                  }, new Response.ErrorListener() {
    
                       @Override
                       public void onErrorResponse(VolleyError error) {
                          display.setText(error.toString());
                          pDialog.hide();
                       }
                    });
    
              // Adding request to request queue
              VolleySingleton.getInstance().addToRequestQueue(jsonObjReq,
                    tag&#95;json&#95;obj);
           }
    

 1 Answer(s)

  • Seems you are passing null for url to the jsonrequest method of volley.

    You may can use this method for making JSONObject request

    public void requestJSON(final RequestCallback callback) {
    
            JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
                    url, null,
                    new Response.Listener<JSONObject>() {
    
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.d(TAG, response.toString());
    
                            /**
                             * todo add your code which will be exicuted on resoponse
                             * or you can send as it is json to the method that called it
                             * like
                             * callback.responseReceived(response);
                             */
    
                        }
                    }, new Response.ErrorListener() {
    
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    // hide the progress dialog
                    /**
                     * todo send call back some error message to show that an error occured while making request.
                     * like
                     *callback.responseReceived(null);
                     */
    
    
                }
            });
    
            // add this request to the volley queue to be executed.
    
            AppInitializer.getContext().getVolleyRequestQueu().add(jsonObjReq);
        }
    

    Find the other files attached to see the implementation.

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: