java开发RESTful接口代码示例详解架构师

java开发RESTful接口代码示例详解架构师
一.用json-lib的jar包输出json串:


public void responseJason(HttpServletResponse response, Object obj){

    ObjectMapper objectMapper = new ObjectMapper();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();// 向OutPutStream中写入                

    try {

        objectMapper.writeValue(baos, obj);// 对象写入json

    } catch (IOException e) {            

        e.printStackTrace();

    }

    response.setContentType(“application/json; charset=utf-8”);

    try {

        response.getWriter().write(baos.toString());

        response.getWriter().flush();

    } catch (IOException e) {

        e.printStackTrace();

    }

}


二.相对应的,来解析json串:

public String getRegionByIP(String ip){

    String url = “http://ip.taobao.com/service/getIpInfo.php?ip=”+ip;

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost httpost = new HttpPost(url);

    String returnRegion = “”;

    try {            

        HttpResponse response = httpClient.execute(httpost);            

        HttpEntity httpEntity = response.getEntity();            

        String responseString = EntityUtils.toString(httpEntity);            

        ObjectMapper objectMapper = new ObjectMapper();

        Map map = objectMapper.readValue(responseString, Map.class);

        Map dataMap = (Map) map.get(“data”);

        String region = dataMap.get(“region”).toString();

        String city = dataMap.get(“city”).toString();

        returnRegion = region+”,”+city;

    } catch (ClientProtocolException e) {

        logger.info(“用IP: “+ip+” 取省市出错!”);

    } catch (IOException e) {    

        //ipFlag = false;            

        logger.info(“用IP: “+ip+” 取省市出错!”);

    } catch (Exception e) {

        //ipFlag = false;            

        logger.info(“用IP: “+ip+” 取省市出错!”);

    }

    return returnRegion;

}

java开发RESTful接口代码示例详解架构师

转载请注明来源网站:blog.ytso.com谢谢!

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/7025.html

(0)
上一篇 2021年7月17日
下一篇 2021年7月17日

相关推荐

发表回复

登录后才能评论