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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM