如何使用Volley库访问宁静的Web服务方法 [英] how to access restful web service methods using volley library

查看:49
本文介绍了如何使用Volley库访问宁静的Web服务方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用本教程 http://www.tutecentral.com/restful-api-for-android-part-1/运行后,我得到了一个自动生成的Java文件,其中包含以下代码.

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://125.0.0.174/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);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setRequestMethod("POST");
    conn.setConnectTimeout(60000);
    Log.e("load r2","load r2");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
    w.write(contents);
    w.flush();
    InputStream istream = conn.getInputStream();
    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_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_Code",mapObject(Terr_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;
}
}

我在异步任务中调用此类,并且一切正常,但是由于异步任务很慢,我想通过凌空使用它. 此类只有一个网址,我不了解如何为单个方法调用此网址,我尝试了以下代码,但出现了异常的网址异常.请告诉我如何使用单独的网址访问rest api的方法.

I'm calling this class in async task and everything is working good but I want to use it through volley as async task is slow. this class has only one url I don't understand how to call this url for individual methods I tried the below code but I'm getting bad url exception. Please show me how access the methods of rest api with separate urls.

public void requestJSON() {

          String tag_json_obj = "json_obj_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) {
                        try {
                             RestAPI restAPI = new RestAPI(); 
                             response = restAPI.GetDoctors(terrcode);                            
                        }   
                        catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                 display.setText(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_json_obj);
       }

推荐答案

将Volley用作VolleyService:

Use Volley as VolleyService :

public class VolleyService {

    private static VolleyService instance;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;

    private VolleyService(Context context) {
        requestQueue = Volley.newRequestQueue(context);

        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url,bitmap);
            }
        });
    }

    public static VolleyService getInstance(Context context) {
        if (instance == null) {
            synchronized(VolleyService.class) {
                if (instance == null) {
                    instance = new VolleyService(context);
                }
            }
        }
        return instance;
    }

    public RequestQueue getRequestQueue() {
        return requestQueue;
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }
}

然后按以下方式在活动"或片段"中使用VolleyService:

Then use your VolleyService in Activity or Fragment as this :

RequestQueue queue = VolleyService.getInstance(this.getContext()).getRequestQueue();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {    
                @Override
                public void onResponse(String response) {
                    // we got the response, now our job is to handle it
                    try {
//Here you parse your JSON - best approach is to use GSON for deserialization
                        getJsonFromResponse(response);
                    } catch (RemoteException | OperationApplicationException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    //something happened, treat the error.
                    Log.e("Error", error.toString());
                }
            });

            queue.add(request);

这篇关于如何使用Volley库访问宁静的Web服务方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆