zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    在servlet中实现页面跳转
    我的jsp学习日记——001:@include(静态包含指令)和jsp:include(动态包含指令)的区别
    myEclipse中修改新建jsp文档的编码格式
    js判断一个图片是否已经存在于缓存中
    MyEclipse的JavaScript提示插件(JSEclipse)
    pku2051 Argus
    pku2084 Game of Connections
    pku2001 Shortest Prefixes
    pku2007 Scrambled Polygon
    pku2153 Rank List
  • 原文地址:https://www.cnblogs.com/zhangfei/p/4202831.html
Copyright © 2011-2022 走看看