客户端与服务器接口的交互。

编程技术  /  houtizong 发布于 3年前   132
DefaultHttpClient httpClient = new DefaultHttpClient();//http://tulogin.erzao.org/tu-login/_____localhost:8080HttpPost method = new HttpPost("http://localhost:8080/tu-login/tuloginMethod");JSONObject jsonParam = new JSONObject();jsonParam.put("phone", phone);jsonParam.put("password", password);jsonParam.put("requrl", requrl);StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");entity.setContentEncoding("UTF-8");entity.setContentType("application/json");method.setEntity(entity);HttpResponse resGet;

上面的代码是设置与服务器连接的,包括连接服务器的方法,以及传输数据的格式,可编码方式等。

下面的代码是处理服务器的返回值的。

try {//通过DefaultHttpClient 来获得返回的参数(值)resGet = httpClient.execute(method);//将返回值设置编码格式,(避免乱码)String resData = EntityUtils.toString(resGet.getEntity(),"utf-8");//通过net.sf.json.JSONObject 来解析字符串JSONObject resJSON = JSONObject.fromObject(resData);//把json中的user对象获取,并强转。Object userjson = resJSON.get("user");String userString = userjson.toString();//通过com.google.gson.Gson 来处理json 类型的user对象。Gson gson = new Gson();//user就是转换后的对象。//在这里,我对com.google.gson.JsonObject有点疑问,为啥这个不能解析返回的字符串呢?//这个类有什么作用?JsonObject jsonObj = new JsonObject();jsonObj.getAsJsonObject(resData);if("A00000".equals(resJSON.get("code"))){User user = gson.fromJson((String) userString, User.class);String token = (String)resJSON.get("token");securityUtil.addCookieToken(request,response,token,user.getId());request.getSession().setAttribute("user", user);}if ( !"A00000".equals(resJSON.get("code"))) {result = resJSON.get("data");}/*else{result = securityUtil.getReqURL(request,response);}*/resultCode = resJSON.get("code");} catch (ClassCastException e) {logger.error(e.getMessage());resultCode = ResultCode.INTERNAL_ERROR;result = e.getMessage();}catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}

再下面是服务器处理请求的。

@RequestMapping(value = "/tuloginMethod")public void login(@RequestBody Map<String, Object> map,HttpServletRequest request, HttpServletResponse response) throws UnAuthedException {response.setCharacterEncoding("UTF-8");String phone = (String) map.get("phone");String password = Md5Util.md5((String) map.get("password"));ResultCode resultCode = ResultCode.SUCCEED;Object result = null;User user = null;String token = null;try {ParamChecker.notEmpty("phone", phone);ParamChecker.notEmpty("password", password);user = UserService.login(request, response, phone, password);token = (String) request.getAttribute("token");} catch (UnAuthedException e) {logger.error(e.getMessage());resultCode = e.getResultCode();result = e.getMessage();} catch (Exception e) {logger.error(e.getMessage(), e);resultCode = ResultCode.INTERNAL_ERROR;result = e.getMessage();}setResponseMethod(response, resultCode, result, user , token);}
对传入的JSON进行解析,并对其进行应有的操作。

并返回值。

下面的代码是最后返回的时候。

 protected void setResponseMethod(HttpServletResponse resp, ResultCode resultCode,            Object result,User user ,String token , String callback) {        try {        resp.setCharacterEncoding("utf-8");            PrintWriter out = resp.getWriter();            Map<String, Object> ret = new LinkedHashMap<String, Object>();            ret.put("code", resultCode.getCode());            ret.put("data", result);            ret.put("user", user);            ret.put("token", token);            String responseStr = GSON.toJson(ret);            out.println(responseStr);            out.close();            resp.setCharacterEncoding("utf-8");                                } catch (Exception e) {            logger.error(e.getMessage(), e);        }    }

OK,这样,客户端与服务器进行交互,传入参数到服务器中进行处理,并返回值到客户端进行处理。

版权声明:本文为博主原创文章,未经博主允许不得转载。

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客