Android 调用 Smart Framework构建的Rest服务

富建章
2023-12-01

首先感谢下 黄勇 大神 写出这么好用的javaweb框架。

Smart Framework详细内容请点击:http://www.oschina.net/p/smart-framework

首先使用smart建立Rest服务的方法,个人分析可用两种方式:

第一种,直接在service层上创建Rest服务

服务端:

@Service
@Rest("/userservice")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class UserServiceImpl implements UserService {

    @POST
    @Path("/login/{username}/{password}")
    @Override
    public void login(@PathParam("username") String username, @PathParam("password") String password) {
        SecurityHelper.login(username, password, false);        
    }
}

android客户端:

public static String sendRequest(HttpRequestMethod methodEnum,
            String url, Map<String, String> paramsMap) {
        String result = null;
        HttpUriRequest req = methodEnum.createRequest(url);
        req.addHeader("Content-Type",MediaType.APPLICATION_JSON); 
        try {
            if (paramsMap != null) {

                JSONObject jsonObj = new JSONObject(paramsMap);
        StringEntity entity = new StringEntity(jsonObj.toString());

        ((HttpEntityEnclosingRequest)req).setEntity(entity);
   }
            HttpResponse httpResp = httpClient.execute(req);
 
            if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
                result = EntityUtils.toString(httpResp.getEntity(), DEFAULT_LOCAL_ENCODE);
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public static String login(String username ,String password){
        return sendRequest(HttpRequestMethod.HttpPost,RootUrl+"/rest/userservice/login/"+username+"/"+password,null);
    }


第二中是在action层上建立Rest服务,这种其实不用建立Rest服务,直接调用action地址即可

直接上android端代码

public static String sendRequest(HttpRequestMethod methodEnum,
            String url, Map<String, String> paramsMap) {
        String result = null;
        HttpUriRequest req = methodEnum.createRequest(url);
         
        try {
            if (paramsMap != null) {

                <span style="color:#ff0000;"><strong>((HttpEntityEnclosingRequest)req).setEntity(new UrlEncodedFormEntity(
                        keyValueToValuePairList(paramsMap), DEFAULT_REMOTE_ENCODE));</strong></span>
   }
            HttpResponse httpResp = httpClient.execute(req);
 
            if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
                result = EntityUtils.toString(httpResp.getEntity(), DEFAULT_LOCAL_ENCODE);
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
       public static String login(String username ,String password){
        Map<String, String> paramsMap = new HashMap<String, String>();
        paramsMap.put("username", "admin");
        paramsMap.put("password", "admin");
        return sendRequest(HttpRequestMethod.HttpPost,RootUrl+"/login,paramsMap);
    }


 类似资料: