如何在Android中制作Api请求包装器

时间:2015-08-11 09:17:38

标签: java android wrapper android-volley

我在swift中有一个应用程序,我创建了一个类ApiRequest来处理我对API的所有调用,因此我在UI中没有任何逻辑,我只返回用于填充视图的对象。

我想在java中做同样的事情,但是据我所知,没有像swift那样的匿名函数或闭包,只有实现接口的匿名对象。所以我试图使用这些概念,凌空和可能的GSON库将我的swift类转换为java类,但我不确定如何完全这样做,或者即使它在java中有意义。< / p>

这是我的快速课程:

class ApiResponse {
    var success: Bool = false
    var message: String = ""
    var data: AnyObject!
}

//The wrapper
class queryAPI {

    var hostname = APP_DELEGATE.hostname

    func requestAPI(url:String, params:String, completion: (ApiResponse) -> ()) {

        let session = NSURLSession.sharedSession()
        let urlStr = hostname+url

        var request = NSMutableURLRequest(URL: NSURL(string:urlStr )!)
        request.HTTPMethod = "POST"

        request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)
        var out = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding)

        request.addValue("XMLHTTPRequest", forHTTPHeaderField: "X-Requested-With")
        request.addValue("KaliMessenger", forHTTPHeaderField: "User-Agent")

        var task = session.dataTaskWithRequest(request){
            (data, response, error) -> Void in

            var res = ApiResponse();

            if error != nil {
                res.success = false
                res.message = error.localizedDescription
                res.data = nil;

                println(error.localizedDescription)

            }
            else {

                var error: NSError?
                println("Performing request: "+urlStr)
                if let  jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary //return a dictionnary with a list of indexes (array)
                {

                    res.success = jsonResult["success"] as! Bool;
                    if(res.success)
                    {
                        res.message = "";
                        res.data = jsonResult["data"]
                    }
                    else
                    {
                        res.message = jsonResult["msg"] as! String;
                        res.data = nil
                    }
                } else {
                    //when we do not manage to get the result, we display the url called, what we have received, and set the response to false
                    var dataContent = NSString(data: data, encoding: NSASCIIStringEncoding);
                    println("Error decoding JSON: ")
                    println(dataContent)
                    res.message = "error decoding json response"
                    res.data = nil
                    res.success = false
                }

            }

            //we return our items to the main thread
            let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
            dispatch_async(dispatch_get_global_queue(priority, 0)){

                dispatch_async(dispatch_get_main_queue()){

                    completion(res)

                }

            }

        }

        task.resume()

    }

     //an example of a function using the wrapper
     func conversationList(completion: ([ModelConversation]) -> ()) {

        self.requestAPI("owapi/messenger/conversationList", params: "") { (res: ApiResponse) -> () in
            var items = [ModelConversation]() //TODO error checking

            if(res.success)
            {
                var data = res.data as! NSArray

                for item in data{
                    let item = ModelConversation(data: item as! NSDictionary)
                    items.append(item)
                }
            }
            completion(items)
        }

    }

}

然后我像这样调用控制器中的函数:

query.allUsers(String(self.first), completion: { (users:[ModelUser]) -> () in
        self.users = users
        self.collectionView.reloadData()
    })

到目前为止我在java中的内容:

public class QueryAPI {

    public class ApiResult
    {
        public Boolean success;
        public String message;
        public Object data;
    }

    public interface ApiResponse<ApiResult>
    {
        public void onCompletion(ApiResult result);
    }

    public void requestApi( String url, final ApiResponse<ModelConversation> completion  )
    {

        JsonObjectRequest apiRequest = new JsonObjectRequest(Request.Method.GET, url, (JSONObject) null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response)
            {

                Log.v("Data: ", response.toString());
                try {
                    Boolean success = response.getBoolean("success");
                    Log.v("Success: ", success.toString());
                    JSONArray data = response.getJSONArray("data");
                    Log.v("DataArray: ", data.toString());
                    ApiResult res = new ApiResult();
                    res.success = success;
                    res.data = data;
                    completion.onCompletion(res);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }
        );
    }

}

任何建议,链接,提示或代码都会很棒!

0 个答案:

没有答案