Java Code Examples for org.nutz.json.Json#fromJson()

The following examples show how to use org.nutz.json.Json#fromJson() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractWxApi2.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
protected void reflushCardTicket() {
    String at = this.getAccessToken();
    String url = String.format("%s/ticket/getticket?access_token=%s&type=wx_card", base, at);
    if (log.isDebugEnabled()) {
    	log.debugf("ATS: reflush wx_card ticket send: %s", url);
    }

    Response resp = Http.get(url);
    if (!resp.isOK()) {
        throw new IllegalArgumentException("reflushCardTicket FAIL , openid=" + openid);
    }
    String str = resp.getContent();

    if (log.isDebugEnabled()) {
        log.debugf("ATS: reflush wx_card ticket done: %s", str);
    }

    NutMap re = Json.fromJson(NutMap.class, str);
    String ticket = re.getString("ticket");
    int expires = re.getInt("expires_in") - 200;//微信默认超时为7200秒,此处设置稍微短一点
    cardTicketStore.save(ticket, expires, System.currentTimeMillis());
}
 
Example 2
Source File: PositionService.java    From flash-waimai with MIT License 6 votes vote down vote up
@Cacheable(value = Cache.APPLICATION ,key = "#root.targetClass.simpleName+':'+#cityName+'-'+#keyword")
public List searchPlace(String cityName, String keyword) {
    logger.info("获取地址信息:{},{}",cityName,keyword);
    Map<String, String> params = Maps.newHashMap();
    params.put("key", appConfiguration.getTencentKey());
    params.put("keyword", URLEncoder.encode(keyword));
    params.put("boundary", "region(" + URLEncoder.encode(cityName) + ",0)");
    params.put("page_size", "10");
    try {
        String str = HttpClients.get(appConfiguration.getQqApiUrl() + "place/v1/search", params);
        Map result = (Map) Json.fromJson(str);
        if (Integer.valueOf(result.get("status").toString()).intValue() == 0) {
            return (List) result.get("data");
        }
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    }
    return null;

}
 
Example 3
Source File: WechatAPIImpl.java    From mpsdk4j with Apache License 2.0 6 votes vote down vote up
@Override
public Follower getWebOauth2User(String openId, String lang) {
    lang = Strings.sBlank(lang, "zh_CN");
    WebOauth2Result result = _oath2.get(openId);
    if (result == null){
       throw Lang.wrapThrow(new WechatAPIException("用户未授权"));
    } else if (!result.isAvailable()){
        result = refreshWebOauth2Result(result.getRefreshToken());
    }

    String url = mergeAPIUrl(oauth2UserURL, result.getAccessToken(), openId, lang);
    APIResult ar = wechatServerResponse(url,
            HTTP_GET,
            NONE_BODY,
            "以网页授权方式获取公众号[%s]的用户[%s-%s]信息失败.",
            openId,
            lang);
    return Json.fromJson(Follower.class, ar.getJson());
}
 
Example 4
Source File: LoachClient.java    From nutzcloud with Apache License 2.0 6 votes vote down vote up
protected boolean _ping() {
    try {
        String pingURL = url + "/ping/" + getServiceName() + "/" + id;
        if (isDebug())
            log.debug("Ping URL=" + pingURL);
        Request req = Request.create(pingURL, METHOD.GET);
        req.getHeader().clear();
        req.getHeader().set("If-None-Match", lastPingETag);
        Response resp = Sender.create(req, conf.getInt("loach.client.ping.timeout", 1000)).setConnTimeout(1000).send();
        String cnt = resp.getContent();
        if (isDebug())
            log.debug("Ping result : " + cnt);
        if (resp.isOK()) {
            lastPingETag = Strings.sBlank(resp.getHeader().get("ETag"), "ABC");
            NutMap re = Json.fromJson(NutMap.class, cnt);
            if (re != null && re.getBoolean("ok", false))
                return true;
        } else if (resp.getStatus() == 304) {
            return true;
        }
    }
    catch (Throwable e) {
        log.debugf("bad url? %s %s", url, e.getMessage());
    }
    return false;
}
 
Example 5
Source File: WxApiImpl.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
protected Map<String, Object> call(String URL, METHOD method, String body) {
    String token = getAccessToken();
    if (URL.contains("?")) {
        URL = base + URL + "&access_token=" + token;
    } else {
        URL = base + URL + "?access_token=" + token;
    }
    Request req = Request.create(URL, method);
    if (body != null)
        req.setData(body);
    Response resp = Sender.create(req).send();
    if (!resp.isOK())
        throw new IllegalArgumentException("resp code=" + resp.getStatus());
    Map<String, Object> map = (Map<String, Object>) Json.fromJson(resp.getReader());
    if (map != null
        && map.containsKey("errcode")
        && ((Number) map.get("errcode")).intValue() != 0) {
        throw new IllegalArgumentException(map.toString());
    }
    return map;
}
 
Example 6
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
@Override
public WxResp add_video(File f, String title, String introduction) {
    if (f == null)
        throw new NullPointerException("meida file is NULL");
    String url = String.format("%s/cgi-bin/material/add_material?type=video&access_token=%s",
                               wxBase,
                               getAccessToken());
    Request req = Request.create(url, METHOD.POST);
    req.getParams().put("media", f);
    req.getParams()
       .put("description",
            Json.toJson(new NutMap().setv("title", title).setv("introduction", introduction),
                        JsonFormat.compact().setQuoteName(true)));
    Response resp = new FilePostSender(req).send();
    if (!resp.isOK())
        throw new IllegalStateException("add_material, resp code=" + resp.getStatus());
    return Json.fromJson(WxResp.class, resp.getReader("UTF-8"));
}
 
Example 7
Source File: WxLoginImpl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp userinfo(String openid, String access_token) {
    // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
    Request req = Request.create("https://api.weixin.qq.com/sns/userinfo", METHOD.GET);
    NutMap params = new NutMap();
    params.put("access_token", access_token);
    params.put("openid", openid);
    req.setParams(params);
    Response resp = Sender.create(req).send();
    if (!resp.isOK()) {
        return null;
    }
    return Json.fromJson(WxResp.class, resp.getReader("UTF-8"));
}
 
Example 8
Source File: APIResult.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
public APIResult(String json) {
    this.json = json;
    this.content = Json.fromJson(Map.class, json);
    this.errCode = (Integer) this.content.get("errcode");
    this.errMsg = (String) this.content.get("errmsg");
    this.errCNMsg = this.errCode == null ? "请求成功." : _cr.get(String.valueOf(this.errCode));

    if (log.isInfoEnabled()) {
        log.infof("Wechat api result: %s", json);
        log.infof("%s", this.getErrCNMsg());
    }
}
 
Example 9
Source File: WechatAPIImpl.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
protected WebOauth2Result refreshWebOauth2Result(String refreshToken) {
    String url = mergeAPIUrl(refreshTokenURL, mpAct.getAppId(), refreshToken);
    APIResult ar = wechatServerResponse(url,
            HTTP_GET,
            NONE_BODY,
            "刷新公众号[%s]的网页授权[%s]凭证信息失败.",
            refreshToken);
    WebOauth2Result result = Json.fromJson(WebOauth2Result.class, ar.getJson());
    _oath2.set(result.getOpenId(), result);
    return result;
}
 
Example 10
Source File: WechatAPIImpl.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Override
public WebOauth2Result getWebOauth2Result(String authCode) {
    String url = mergeAPIUrl(oauth2URL, mpAct.getAppId(), mpAct.getAppSecret(), authCode);
    APIResult ar = wechatServerResponse(url,
            HTTP_GET,
            "换取公众号[%s]授权码[%s]凭证信息失败.",
            authCode);
    WebOauth2Result result = Json.fromJson(WebOauth2Result.class, ar.getJson());
    _oath2.set(result.getOpenId(), result);
    return result;
}
 
Example 11
Source File: WechatAPIImpl.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Override
public Follower getFollower(String openId, String lang) {
    lang = Strings.sBlank(lang, "zh_CN");
    String url = mergeCgiBinUrl(userInfoURL, getAccessToken(), openId, lang);
    APIResult ar = wechatServerResponse(url,
            HTTP_GET,
            NONE_BODY,
            "获取公众号[%s]关注用户[%s-%s]信息失败.",
            openId,
            lang);
    return Json.fromJson(Follower.class, ar.getJson());
}
 
Example 12
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp kfaccount_uploadheadimg(String kf_account, File f) {
    if (f == null)
        throw new NullPointerException("meida file is NULL");
    String url = String.format("%s/customservice/kfaccount/uploadheadimg?access_token=%s",
                               wxBase,
                               getAccessToken());
    Request req = Request.create(url, METHOD.POST);
    req.getParams().put("media", f);
    Response resp = new FilePostSender(req).send();
    if (!resp.isOK())
        throw new IllegalStateException("uploadimg, resp code=" + resp.getStatus());
    return Json.fromJson(WxResp.class, resp.getReader("UTF-8"));
}
 
Example 13
Source File: WechatAPIImpl.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Override
public Media upMedia(String type, File media) {
    String url = mergeCgiBinUrl(uploadMediaURL, getAccessToken(), type);
    APIResult ar = wechatServerResponse(url,
            HTTP_UPLOAD,
            media,
            "上传公众号[%s]的多媒体文件[%s]失败.",
            media.getName());
    return Json.fromJson(Media.class, ar.getJson());
}
 
Example 14
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp media_upload(String type, File f) {
    if (type == null)
        throw new NullPointerException("media type is NULL");
    if (f == null)
        throw new NullPointerException("meida file is NULL");
    String url = String.format("%s/cgi-bin/media/upload?access_token=%s&type=%s", wxBase, getAccessToken(), type);
    Request req = Request.create(url, METHOD.POST);
    req.getParams().put("media", f);
    Response resp = new FilePostSender(req).send();
    if (!resp.isOK())
        throw new IllegalStateException("media upload file, resp code=" + resp.getStatus());
    return Json.fromJson(WxResp.class, resp.getReader("UTF-8"));
}
 
Example 15
Source File: LoachClient.java    From nutzcloud with Apache License 2.0 5 votes vote down vote up
protected boolean _reg(String regData) {
    try {
        String regURL = url + "/reg";
        if (isDebug()) {
            log.debug("Reg URL :" + regURL);
            log.debug("Reg Data:" + regData);
        }
        Request req = Request.create(regURL, METHOD.POST);
        req.setData(regData);
        req.getHeader().clear();
        req.getHeader().asJsonContentType();
        Response resp = Sender.create(req).setTimeout(3000).send();
        if (resp.isOK()) {
            NutMap re = Json.fromJson(NutMap.class, resp.getReader());
            if (re != null && re.getBoolean("ok", false)) {
                log.infof("Reg Done id=%s url=%s", id, url);
                regOk = true;
                return true;
            }
            else if (re == null) {
                log.info("Reg Err, revc NULL");
                return false;
            }
            else {
                log.info("Reg Err " + re);
                return false;
            }
        }
    }
    catch (Throwable e) {
        log.debugf("bad url? %s %s", url, e.getMessage());
    }
    return false;
}
 
Example 16
Source File: PositionService.java    From flash-waimai with MIT License 5 votes vote down vote up
public Map<String,String> getDistance(String from,String to){
    Map<String,String> params = Maps.newHashMap(
            "ak",appConfiguration.getBaiduKey(),
            "output","json",
            "origins",from,
            "destinations",to
    );
    try {
        //使用百度地图api获取距离值:
        //routematrix/v2/riding 骑行
        //routematrix/v2/driving 开车
        //routematrix/v2/walking 步行
        String str = HttpClients.get(appConfiguration.getBaiduApiUrl() + "routematrix/v2/riding", params);
        Map response = (Map) Json.fromJson(str);
        if("0".equals(response.get("status").toString())){
          Map result =  Maps.newHashMap(
                  "distance",Mapl.cell(response,"result[0].distance.text"),
                  "duration",Mapl.cell(response,"result[0].duration.text")
          );
          return result;
        }

    }catch (Exception e){
        logger.error("通过百度获取配送距离失败",e);
    }
    return null;
}
 
Example 17
Source File: PositionService.java    From flash-waimai with MIT License 5 votes vote down vote up
/**
 * 根据经纬度坐标获取位置信息
 *
 * @param geohash
 * @return
 */

@Cacheable(value = Cache.APPLICATION ,key = "#root.targetClass.simpleName+':'+#geohash")
public Map pois(String geohash) {
    logger.info("获取地址信息:{}",geohash);
    Map<String, String> map = Maps.newHashMap();
    map.put("location", geohash);
    map.put("key", appConfiguration.getTencentKey());
    Map result = Maps.newHashMap();
    try {
        String str = HttpClients.get(appConfiguration.getQqApiUrl() + "geocoder/v1", map);
        Map response = (Map) Json.fromJson(str);
        if ("0".equals(response.get("status").toString())) {
            result.put("address", Mapl.cell(response,"result.address"));
            result.put("city", Mapl.cell(response, "result.address_component.city"));
            result.put("name", Mapl.cell(response, "result.formatted_addresses.recommend"));
            result.put("latitude", Mapl.cell(response, "result.location.lat"));
            result.put("longitude", Mapl.cell(response, "result.location.lng"));
        }else{
            logger.error("获取地理位置信息失败:{}",str);
        }

    } catch (Exception e) {
        logger.error("获取地理位置异常", e);
    }
    return result;
}
 
Example 18
Source File: BankCardUtils.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
/**
 * 支付宝 验证银行卡
 * @param cardId
 * @return
 */
public static CardInfoData validateAndCacheCardInfo(String cardId){
    cardId = cardId.replaceAll(" ", "");
    String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardBinCheck=true&cardNo="+ cardId;
    String res = Http.get(url,5000).getContent();
    System.out.println(res);
    CardInfoData cardInfoData = new CardInfoData();
    if(Strings.isNotBlank(res)){
        cardInfoData = Json.fromJson(CardInfoData.class, res);
    }
    return cardInfoData;
}
 
Example 19
Source File: AbstractWxApi2.java    From nutzwx with Apache License 2.0 4 votes vote down vote up
protected WxResp call(String URL, METHOD method, String body) {
    String token = getAccessToken();
    if (log.isInfoEnabled()) {
        log.info("wxapi call: " + URL);
        if (log.isDebugEnabled()) {
            log.debug(body);
        }
    }

    int retry = retryTimes;
    WxResp wxResp = null;
    while (retry >= 0) {
        try {
            String sendUrl = URL.startsWith("http") ? URL : base + URL;
            if (URL.contains("?")) {
                sendUrl += "&access_token=" + token;
            } else {
                sendUrl += "?access_token=" + token;
            }
            Request req = Request.create(sendUrl, method);
            if (body != null)
                req.setData(body);
            Response resp = Sender.create(req).send();
            if (!resp.isOK())
                throw new IllegalArgumentException("resp code=" + resp.getStatus());
            wxResp = Json.fromJson(WxResp.class, resp.getReader("UTF-8"));
            // 处理微信返回  40001 invalid credential
            if (wxResp.errcode() != 40001) {
                break;//正常直接返回
            } else {
                log.warnf("wxapi of access_token request [%s] finished, but the return code is 40001, try to reflush access_token right now, surplus retry times : %s", URL, retry);
                // 强制刷新一次acess_token
                reflushAccessToken();
            }
        } catch (Exception e) {
            if (retry >= 0) {
                log.warn("reflushing access_token... " + retry + " retries left.", e);
            } else {
                log.errorf("%s times attempts to get a wx access_token , but all failed!", retryTimes);
                throw Lang.wrapThrow(e);
            }
        } finally {
            retry--;
        }
    }
    return wxResp;
}
 
Example 20
Source File: TaobaoIP.java    From BigDataPlatform with GNU General Public License v3.0 4 votes vote down vote up
public static TaobaoIPResult getResult(String ip) {
  Response response = Http.get("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
  TaobaoIPResult result = new TaobaoIPResult();
  if (ip != null && response.getStatus() == 200) {
    try {
      String content = response.getContent();
      Map<String, Object> contentMap = (Map)Json.fromJson(content);
      if (((Integer)((Integer)contentMap.get("code"))).intValue() == 0) {
        Map<String, Object> dataMap = (Map)contentMap.get("data");
        result.setCountry((String)dataMap.get("country"));
        result.setRegion((String)dataMap.get("region"));
        result.setCity((String)dataMap.get("city"));
        result.setCounty((String)dataMap.get("county"));
        result.setIsp((String)dataMap.get("isp"));
        result.setArea((String)dataMap.get("area"));
        result.setIp((String)dataMap.get("ip"));
        result.setCode(0);

        if (result.getCity().equals("内网IP") && result.getIsp().equals("内网IP")){
          result.setCode(0);
          result.setCountry("中国");
          result.setRegion("广东");
          result.setCity("东莞");
          result.setCounty("XX");
          result.setIsp("casc");
          result.setArea("XX");
          result.setIp(ip);
        }

        return result;
      }
    } catch (Exception var6) {
    }
  }

    result.setCode(-1);
    result.setCountry("XX");
    result.setRegion("XX");
    result.setCity("XX");
    result.setCounty("XX");
    result.setIsp("XX");
    result.setArea("XX");
    result.setIp(ip);
  return result;
}