org.nutz.http.Response Java Examples
The following examples show how to use
org.nutz.http.Response.
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 |
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: WxApi2Impl.java From nutzwx with Apache License 2.0 | 6 votes |
/** * 微信支付公共POST方法(带证书) * * @param url * 请求路径 * @param key * 商户KEY * @param params * 参数 * @param file * 证书文件 * @param password * 证书密码 * @return */ @Override public NutMap postPay(String url, String key, Map<String, Object> params, Object data, String password) { params.remove("sign"); String sign = WxPaySign.createSign(key, params); params.put("sign", sign); Request req = Request.create(url, METHOD.POST); req.setData(Xmls.mapToXml(params)); Sender sender = Sender.create(req); SSLSocketFactory sslSocketFactory; try { sslSocketFactory = WxPaySSL.buildSSL(data, password); } catch (Exception e) { throw Lang.wrapThrow(e); } sender.setSSLSocketFactory(sslSocketFactory); Response resp = sender.send(); if (!resp.isOK()) throw new IllegalStateException("postPay with SSL, resp code=" + resp.getStatus()); return Xmls.xmlToMap(resp.getContent("UTF-8")); }
Example #3
Source File: WxApi2Impl.java From nutzwx with Apache License 2.0 | 6 votes |
@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 #4
Source File: WxApiImpl.java From nutzwx with Apache License 2.0 | 6 votes |
@Override public String mediaUpload(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("http://file.api.weixin.qq.com/cgi-bin/media/upload?token=%s&type=%s", 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()); 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.get("media_id").toString(); }
Example #5
Source File: WxApiImpl.java From nutzwx with Apache License 2.0 | 6 votes |
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: WxApiImpl.java From nutzwx with Apache License 2.0 | 6 votes |
public void reflushAccessToken() { String url = String.format("%s/token?grant_type=client_credential&appid=%s&secret=%s", base, master.getAppid(), master.getAppsecret()); Response resp = Http.get(url); if (!resp.isOK()) throw new IllegalArgumentException("reflushAccessToken FAIL , openid=" + master.getOpenid()); String str = resp.getContent(); Map<String, Object> map = (Map<String, Object>) Json.fromJson(str); master.setAccess_token(map.get("token").toString()); master.setAccess_token_expires(System.currentTimeMillis() + (((Number) map.get("expires_in")).intValue() - 60) * 1000); }
Example #7
Source File: AbstractWxApi2.java From nutzwx with Apache License 2.0 | 6 votes |
protected synchronized void reflushAccessToken() { String url = String.format("%s/token?grant_type=client_credential&appid=%s&secret=%s", base, appid, appsecret); if (log.isDebugEnabled()) log.debugf("ATS: reflush access_token send: %s", url); Response resp = Http.get(url); if (!resp.isOK()) throw new IllegalArgumentException("reflushAccessToken FAIL , openid=" + openid); String str = resp.getContent(); if (log.isDebugEnabled()) log.debugf("ATS: reflush access_token done: %s", str); NutMap re = Json.fromJson(NutMap.class, str); if(re.getInt("errcode", 0)!=0) throw new IllegalArgumentException("reflushAccessToken FAIL : " + str); String token = re.getString("access_token"); int expires = re.getInt("expires_in") - 200;//微信默认超时为7200秒,此处设置稍微短一点 accessTokenStore.save(token, expires, System.currentTimeMillis()); }
Example #8
Source File: AbstractWxApi2.java From nutzwx with Apache License 2.0 | 6 votes |
protected void reflushJsapiTicket() { String at = this.getAccessToken(); String url = String.format("%s/ticket/getticket?access_token=%s&type=jsapi", base, at); if (log.isDebugEnabled()) log.debugf("ATS: reflush jsapi ticket send: %s", url); Response resp = Http.get(url); if (!resp.isOK()) throw new IllegalArgumentException("reflushJsapiTicket FAIL , openid=" + openid); String str = resp.getContent(); if (log.isDebugEnabled()) log.debugf("ATS: reflush jsapi ticket done: %s", str); NutMap re = Json.fromJson(NutMap.class, str); String ticket = re.getString("ticket"); int expires = re.getInt("expires_in") - 200;//微信默认超时为7200秒,此处设置稍微短一点 jsapiTicketStore.save(ticket, expires, System.currentTimeMillis()); }
Example #9
Source File: LoachClient.java From nutzcloud with Apache License 2.0 | 6 votes |
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 #10
Source File: AddressUtils.java From NutzSite with Apache License 2.0 | 6 votes |
public static String getRealAddressByIP(String ip) { String address = "XX XX"; // 内网不查询 if (IpUtils.internalIp(ip)) { return "内网IP"; } try { Response rspStr = Http.get(IP_URL + "?ip=" + ip, 5 * 1000); if (!rspStr.isOK()) { log.error("获取地理位置异常 {}", ip); return address; } JSONObject obj = JSONObject.parseObject(rspStr.getContent()); JSONObject data = obj.getObject("data", JSONObject.class); String region = data.getString("region"); String city = data.getString("city"); address = region + " " + city; } catch (Exception e) { log.error("IP查询失败:" + ip + e.getMessage()); } return address; }
Example #11
Source File: HttpTool.java From mpsdk4j with Apache License 2.0 | 6 votes |
public static String upload(String url, File file) { if (log.isDebugEnabled()) { log.debugf("Upload url: %s, file name: %s, default timeout: %d", url, file.getName(), CONNECT_TIME_OUT); } try { Request req = Request.create(url, METHOD.POST); req.getParams().put("media", file); Response resp = new FilePostSender(req).send(); if (resp.isOK()) { String content = resp.getContent(); return content; } throw Lang.wrapThrow(new RuntimeException(String.format("Upload file [%s] failed. status: %d", url, resp.getStatus()))); } catch (Exception e) { throw Lang.wrapThrow(e); } }
Example #12
Source File: LoachClient.java From nutzcloud with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public void updateServiceList() { try { String listURL = url + "/list"; Request req = Request.create(listURL, METHOD.GET); req.getHeader().clear(); req.getHeader().set("If-None-Match", lastListETag); Response resp = Sender.create(req).setConnTimeout(1000).setTimeout(3000).send(); if (resp.isOK()) { serviceList = (Map<String, List<NutMap>>) Json.fromJson(NutMap.class, resp.getReader()).get("data"); for (UpdateListener listener : listeners) { listener.onUpdate(serviceList); } lastChecked = System.currentTimeMillis(); lastListETag = Strings.sBlank(resp.getHeader().get("ETag", "ABC")); } else if (resp.getStatus() == 304) { // ok lastChecked = System.currentTimeMillis(); } } catch (Throwable e) { log.debugf("bad url? %s %s", url, e.getMessage()); } }
Example #13
Source File: HttpTool.java From mpsdk4j with Apache License 2.0 | 6 votes |
public static String get(String url) { if (log.isDebugEnabled()) { log.debugf("Request url: %s, default timeout: %d", url, CONNECT_TIME_OUT); } try { Response resp = Http.get(url, CONNECT_TIME_OUT); if (resp.isOK()) { String content = resp.getContent("UTF-8"); if (log.isInfoEnabled()) { log.infof("GET Request success. Response content: %s", content); } return content; } throw Lang.wrapThrow(new RuntimeException(String.format("Get request [%s] failed. status: %d", url, resp.getStatus()))); } catch (Exception e) { throw Lang.wrapThrow(e); } }
Example #14
Source File: HttpTool.java From mpsdk4j with Apache License 2.0 | 5 votes |
public static String post(String url, String body) { if (log.isDebugEnabled()) { log.debugf("Request url: %s, post data: %s, default timeout: %d", url, body, CONNECT_TIME_OUT); } try { Request req = Request.create(url, METHOD.POST); req.setEnc("UTF-8"); req.setData(body); Response resp = Sender.create(req, CONNECT_TIME_OUT).send(); if (resp.isOK()) { String content = resp.getContent(); if (log.isInfoEnabled()) { log.infof("POST Request success. Response content: %s", content); } return content; } throw Lang.wrapThrow(new RuntimeException(String.format("Post request [%s] failed. status: %d", url, resp.getStatus()))); } catch (Exception e) { throw Lang.wrapThrow(e); } }
Example #15
Source File: SenderSendInterceptor.java From skywalking with Apache License 2.0 | 5 votes |
@Override public Object afterMethod(final EnhancedInstance objInst, final Method method, final Object[] allArguments, final Class<?>[] argumentsTypes, Object ret) throws Throwable { Response response = (Response) ret; int statusCode = response.getStatus(); AbstractSpan span = ContextManager.activeSpan(); if (statusCode >= 400) { span.errorOccurred(); Tags.STATUS_CODE.set(span, Integer.toString(statusCode)); } ContextManager.stopSpan(); return ret; }
Example #16
Source File: WxLoginImpl.java From nutzwx with Apache License 2.0 | 5 votes |
@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 #17
Source File: WxLoginImpl.java From nutzwx with Apache License 2.0 | 5 votes |
@Override public WxResp access_token(String code) { Request req = Request.create("https://api.weixin.qq.com/sns/oauth2/access_token", METHOD.GET); NutMap params = new NutMap(); params.put("appid", appid); params.put("secret", appsecret); params.put("code", code); params.put("grant_type", "authorization_code"); req.setParams(params); Response resp = Sender.create(req).send(); if (!resp.isOK()) { return null; } return Json.fromJson(WxResp.class, resp.getReader("UTF-8")); }
Example #18
Source File: WxApiImpl.java From nutzwx with Apache License 2.0 | 5 votes |
@Override public NutResource mediaGet(String mediaId) { String url = "http://file.api.weixin.qq.com/cgi-bin/media/get"; Map<String, Object> params = new HashMap<String, Object>(); params.put("token", getAccessToken()); params.put("media_id", mediaId); final Response resp = Sender.create(Request.create(url, METHOD.GET)).send(); if (!resp.isOK()) throw new IllegalStateException("download media file, resp code=" + resp.getStatus()); final String disposition = resp.getHeader().get("Content-disposition"); return new NutResource() { public String getName() { if (disposition == null) return "file.data"; for (String str : disposition.split(";")) { if (str.startsWith("filename=")) { str = str.substring("filename=".length()); if (str.startsWith("\"")) str = str.substring(1); if (str.endsWith("\"")) str = str.substring(0, str.length() - 1); return str.trim().intern(); } } return "file.data"; } public InputStream getInputStream() throws IOException { return resp.getStream(); } }; }
Example #19
Source File: WxApi2Impl.java From nutzwx with Apache License 2.0 | 5 votes |
@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 #20
Source File: WxApi2Impl.java From nutzwx with Apache License 2.0 | 5 votes |
@Override public NutResource media_get(String mediaId) { String url = String.format("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s", getAccessToken(), mediaId); final Response resp = Sender.create(Request.create(url, METHOD.GET)).send(); if (!resp.isOK()) throw new IllegalStateException("download media file, resp code=" + resp.getStatus()); String disposition = resp.getHeader().get("Content-disposition"); return new WxResource(disposition, resp.getStream()); }
Example #21
Source File: WxApi2Impl.java From nutzwx with Apache License 2.0 | 5 votes |
@Override public WxResp uploadimg(File f) { if (f == null) throw new NullPointerException("meida file is NULL"); String url = String.format("%s/cgi-bin/media/uploadimg?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 #22
Source File: WxApi2Impl.java From nutzwx with Apache License 2.0 | 5 votes |
@Override public WxResp add_material(String type, File f) { if (f == null) throw new NullPointerException("meida file is NULL"); String url = String.format("%s/cgi-bin/material/add_material?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("add_material, resp code=" + resp.getStatus()); return Json.fromJson(WxResp.class, resp.getReader("UTF-8")); }
Example #23
Source File: LoachClient.java From nutzcloud with Apache License 2.0 | 5 votes |
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 #24
Source File: WxApi2Impl.java From nutzwx with Apache License 2.0 | 5 votes |
@Override public NutResource get_material(String media_id) { String url = String.format("%s/cgi-bin/material/get_material?access_token=%s", wxBase, getAccessToken()); Request req = Request.create(url, METHOD.POST); NutMap body = new NutMap(); body.put("media_id", media_id); req.setData(Json.toJson(body)); final Response resp = Sender.create(req).send(); if (!resp.isOK()) throw new IllegalStateException("download media file, resp code=" + resp.getStatus()); String disposition = resp.getHeader().get("Content-disposition"); return new WxResource(disposition, resp.getStream()); }
Example #25
Source File: WxApi2Impl.java From nutzwx with Apache License 2.0 | 5 votes |
@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 #26
Source File: WxApi2Impl.java From nutzwx with Apache License 2.0 | 5 votes |
/** * 微信支付公共POST方法(不带证书) * * @param url * 请求路径 * @param key * 商户KEY * @param params * 参数 * @return */ @Override public NutMap postPay(String url, String key, Map<String, Object> params) { params.remove("sign"); String sign = WxPaySign.createSign(key, params); params.put("sign", sign); Request req = Request.create(url, METHOD.POST); req.setData(Xmls.mapToXml(params)); Response resp = Sender.create(req).send(); if (!resp.isOK()) throw new IllegalStateException("postPay, resp code=" + resp.getStatus()); return Xmls.xmlToMap(resp.getContent("UTF-8")); }
Example #27
Source File: TaobaoIP.java From BigDataPlatform with GNU General Public License v3.0 | 4 votes |
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; }
Example #28
Source File: AbstractWxApi2.java From nutzwx with Apache License 2.0 | 4 votes |
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 #29
Source File: HttpTool.java From mpsdk4j with Apache License 2.0 | 4 votes |
public static Object download(String url) { if (log.isDebugEnabled()) { log.debugf("Download url: %s, default timeout: %d", url, CONNECT_TIME_OUT); } try { Response resp = Http.get(url); if (resp.isOK()) { String cd = resp.getHeader().get("Content-disposition"); if (log.isInfoEnabled()) { log.infof("Get download file info: %s", cd); } if (Lang.isEmpty(cd)) { return resp.getContent(); } cd = cd.substring(cd.indexOf(FILE_NAME_FLAG) + FILE_NAME_FLAG.length()); String tmp = cd.startsWith("\"") ? cd.substring(1) : cd; tmp = tmp.endsWith("\"") ? cd.replace("\"", "") : cd; String filename = tmp.substring(0, tmp.lastIndexOf(".")); String fileext = tmp.substring(tmp.lastIndexOf(".")); if (log.isInfoEnabled()) { log.infof("Download file name: %s", filename); log.infof("Download file ext: %s", fileext); } File tmpfile = File.createTempFile(filename, fileext); InputStream is = resp.getStream(); OutputStream os = new FileOutputStream(tmpfile); Streams.writeAndClose(os, is); return tmpfile; } throw Lang.wrapThrow(new RuntimeException(String.format("Download file [%s] failed. status: %d, content: %s", url, resp.getStatus(), resp.getContent()))); } catch (Exception e) { throw Lang.wrapThrow(e); } }