Java Code Examples for net.sf.json.JSONObject#getInt()
The following examples show how to use
net.sf.json.JSONObject#getInt() .
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: JwShopAPI.java From jeewx-api with Apache License 2.0 | 6 votes |
/** * 上传图片 * @param fileName * @param accountid * @return */ public static String uploadImg(String newAccessToken, String filePath, String fileName) { if (newAccessToken != null) { String requestUrl = upload_img_shop_url.replace("ACCESS_TOKEN", newAccessToken); byte[] fileByte; try { fileByte = fileData(filePath+fileName); JSONObject result = WxstoreUtils.httpRequest2(requestUrl, "POST", fileByte); if (result.getInt("errcode") == 0) { return result.getString("url"); } return ""; } catch (IOException e) { e.printStackTrace(); } } return ""; }
Example 2
Source File: ZAProxyBuilder.java From zaproxy-plugin with MIT License | 6 votes |
@Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { // To persist global configuration information, // set that to properties and call save(). zapProxyDefaultHost = formData.getString("zapProxyDefaultHost"); zapProxyDefaultPort = formData.getInt("zapProxyDefaultPort"); //set the values from the global configuration for CREATE JIRA ISSUES jiraBaseURL=formData.getString("jiraBaseURL"); jiraUserName=formData.getString("jiraUserName"); jiraPassword=formData.getString("jiraPassword"); // ^Can also use req.bindJSON(this, formData); // (easier when there are many fields; need set* methods for this, like setUseFrench) save(); return super.configure(req,formData); }
Example 3
Source File: DescriptorImpl.java From qy-wechat-notification-plugin with Apache License 2.0 | 6 votes |
@Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { config.webhookUrl = json.getString("webhookUrl"); config.topicName = json.getString("topicName"); config.mentionedId = json.getString("mentionedId"); config.mentionedMobile = json.getString("mentionedMobile"); config.useProxy = json.get("useProxy")!=null; if(config.useProxy && json.get("useProxy") instanceof JSONObject){ JSONObject jsonObject = json.getJSONObject("useProxy"); config.proxyHost = jsonObject.getString("proxyHost"); config.proxyPort = jsonObject.getInt("proxyPort"); config.proxyUsername = jsonObject.getString("proxyUsername"); config.proxyPassword = Secret.fromString(jsonObject.getString("proxyPassword")); } save(); return super.configure(req, json); }
Example 4
Source File: ConceptMapping.java From Criteria2Query with Apache License 2.0 | 6 votes |
public String[] getCloestConceptByUsagi(String term,String domain){ String[] res=new String[3]; JSONObject jo=new JSONObject(); jo.accumulate("term", StringUtil.cleanASCII(term)); jo.accumulate("domain", domain); String result=HttpUtil.doPost(usagi, jo.toString()); System.out.println(jo.toString()); System.out.println("result="+result); JSONObject bestconcept=JSONObject.fromObject(result); System.out.println("matchScore="+bestconcept.getDouble("matchScore")); String matchs=String.format("%.2f", bestconcept.getDouble("matchScore")*100); JSONObject concept_jo=bestconcept.getJSONObject("concept"); Integer cId=concept_jo.getInt("conceptId"); String conceptname=concept_jo.getString("conceptName"); res[0]=String.valueOf(cId); res[1]=conceptname; res[2]=matchs; return res; }
Example 5
Source File: JwSendMessageAPI.java From jeewx-api with Apache License 2.0 | 5 votes |
/** * 语音,图片,视频消息预览 * * @param touser * @param wxArticles * @throws Exception */ public static void messagePrivate(String accesstoken, String touser, WxMedia wxMedia) throws WexinReqException { if (accesstoken != null) { String requestUrl = message_preview_url.replace("ACCESS_TOKEN", accesstoken); try { String mediaId = getMediaId(accesstoken, wxMedia); JSONObject obj = new JSONObject(); JSONObject type = new JSONObject(); obj.put("touser", touser); obj.put("msgtype", wxMedia.getType()); type.put("media_id", mediaId); obj.put(wxMedia.getType(), type); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); //System.out.println("微信返回的结果:" + result.toString()); if (result.getInt("errcode") != 0) { logger.error("多媒体消息预览失败!errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg")); throw new Exception("多媒体消息预览失败!errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg")); } } catch (Exception e) { throw new WexinReqException(e); } } else { throw new WexinReqException("accesstoken 为空,请检查!"); } }
Example 6
Source File: JwMediaAPI.java From jeewx-api with Apache License 2.0 | 5 votes |
/** * 删除永久素材 * * @param accesstoken * @param mediaId * 图文集合,数量不大于10 * @return WxArticlesRespponseByMaterial 上传图文消息素材返回结果 * @throws WexinReqException */ public static void deleteArticlesByMaterialNews(String accesstoken,String mediaId) throws WexinReqException { if (accesstoken != null&&StringUtils.isNotEmpty(mediaId)) { String requestUrl = material_del_news_url.replace("ACCESS_TOKEN", accesstoken); JSONObject obj = new JSONObject(); obj.put("media_id", mediaId); JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString()); if (result.has("errcode")&&result.getInt("errcode")!=0) { logger.error("=====删除永久素材失败!errcode=" + result.getString("errcode") + ",errmsg = " + result.getString("errmsg")+"======"); throw new WexinReqException(result.getString("errcode")); }else{ logger.info("=====删除永久素材成功====="); } } }
Example 7
Source File: JwUserAPI.java From jeewx-api with Apache License 2.0 | 5 votes |
/** * 获取所有关注用户信息信息 * * @return * @throws WexinReqException */ public static List<Wxuser> getAllWxuser(String accesstoken,String next_openid) throws WexinReqException { if (accesstoken != null) { UserInfoListGet userInfoListGet = new UserInfoListGet(); userInfoListGet.setAccess_token(accesstoken); userInfoListGet.setNext_openid(next_openid); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(userInfoListGet); Object error = result.get("errcode"); List<Wxuser> lstUser = null; Wxuser mxuser = null; int total = result.getInt("total"); int count = result.getInt("count"); String strNextOpenId = result.getString("next_openid"); JSONObject data = result.getJSONObject("data"); lstUser = new ArrayList<Wxuser>(total); if (count > 0) { JSONArray lstOpenid = data.getJSONArray("openid"); int iSize = lstOpenid.size(); for (int i = 0; i < iSize; i++) { String openId = lstOpenid.getString(i); mxuser = getWxuser(accesstoken, openId); lstUser.add(mxuser); } if (strNextOpenId != null) { lstUser.addAll(getAllWxuser(accesstoken, strNextOpenId)); } } return lstUser; } return null; }
Example 8
Source File: BlazeMeterAPIClient.java From jmeter-bzm-plugins with Apache License 2.0 | 5 votes |
public void sendOnlineData(JSONObject data) throws IOException { JSONObject session = test.getSession().sendData(data); int statusCode = session.getInt("statusCode"); if (statusCode > 100) { notifier.notifyAbout("Test was stopped through Web UI: " + session.getString("status")); throw new JMeterStopTestException("The test was interrupted through Web UI"); } }
Example 9
Source File: RefReplicationDone.java From gerrit-events with MIT License | 5 votes |
@Override public void fromJson(JSONObject json) { project = getString(json, PROJECT); ref = getString(json, REF); nodesCount = json.getInt(NODES_COUNT); super.fromJson(json); }
Example 10
Source File: JsonSecurityRule.java From ipst with Mozilla Public License 2.0 | 5 votes |
public static SecurityRule fromJSON(JSONObject json) { return new JsonSecurityRule( new RuleId(RuleAttributeSet.valueOf(json.getString("algoType")), new SecurityIndexId(json.getString("contingencyId"), SecurityIndexType.fromLabel(json.getString("indexType")))), json.getString("workflowId"), (float) json.getDouble("quality"), json.getInt("treeSize"), (float) json.getDouble("criticality"), json.getJSONObject("tree") ); }
Example 11
Source File: Engine.java From acunetix-plugin with MIT License | 5 votes |
public Integer getVersion() throws IOException { if (apiUrl.matches(":\\d+")) { JSONObject jso = doGet(apiUrl + "/info").jso; return jso.getInt("major_version"); } else { return 13; } }
Example 12
Source File: ContentReviewServiceTurnitinOC.java From sakai with Educational Community License v2.0 | 4 votes |
private int getSimilarityReportStatus(String reportId) throws Exception { HashMap<String, Object> response = makeHttpCall("GET", getNormalizedServiceUrl() + "submissions/" + reportId + "/similarity", BASE_HEADERS, null, null); // Get response: int responseCode = !response.containsKey(RESPONSE_CODE) ? 0 : (int) response.get(RESPONSE_CODE); String responseMessage = !response.containsKey(RESPONSE_MESSAGE) ? "" : (String) response.get(RESPONSE_MESSAGE); String responseBody = !response.containsKey(RESPONSE_BODY) ? "" : (String) response.get(RESPONSE_BODY); // create JSONObject from response JSONObject responseJSON = JSONObject.fromObject(responseBody); if ((responseCode >= 200) && (responseCode < 300)) { // See if report is complete or pending. If pending, ignore, if complete, get // score and viewer URL if (responseJSON.containsKey("status") && responseJSON.getString("status").equals(STATUS_COMPLETE)) { log.debug("Submission successful"); if (responseJSON.containsKey("overall_match_percentage")) { return responseJSON.getInt("overall_match_percentage"); } else { log.error("Report came back as complete, but without a score"); return -2; } } else if (responseJSON.containsKey("status") && responseJSON.getString("status").equals(STATUS_PROCESSING)) { log.debug("report is processing..."); return -1; } else { log.error("Something went wrong in the similarity report process: reportId " + reportId); return -2; } } else { log.error("Submission status call failed: " + responseMessage); return -2; } }
Example 13
Source File: MainController.java From ApiManager with GNU Affero General Public License v3.0 | 4 votes |
/** * 获取系统最新信息 * * @return * @throws Exception */ @RequestMapping("/admin/property.do") @AuthPassport(authority = C_AUTH_SETTING) @ResponseBody public JsonResult property() throws Exception { Map<String, Object> returnMap = new HashMap<>(); Map<String, Object> properties = new HashMap<>(); properties.put("domain", Tools.getUrlPath()); properties.put("openRegister", Config.openRegister); properties.put("luceneSearchNeedLogin", Config.luceneSearchNeedLogin); properties.put("openRegister", Config.openRegister); properties.put("canRepeatUrl", Config.canRepeatUrl); properties.put("cacheTime", Config.cacheTime); properties.put("loginInforTime", Config.loginInforTime); properties.put("fileSize", Config.fileSize); properties.put("fileType", Config.fileType); properties.put("imageType", Config.imageType); properties.put("mail", Config.mail); properties.put("clientID", Config.clientID); returnMap.put("properties", properties); // 从crapApi获取版本信息 try { String crapApiInfo = HttpPostGet.get("http://api.crap.cn/mock/trueExam.do?id=c107b205-c365-4050-8fa9-dbb7a38b3d11&cache=true", null, null); JSONObject json = JSONObject.fromObject(crapApiInfo); if (json.getInt("success") == 1) { json = json.getJSONObject("data"); returnMap.put("crapApiInfo", Tools.getStrMap("latestVersion", json.getString("latestVersion"), "latestVersion", json.getString("latestVersion"), "addFunction", json.getString("addFunction"), "updateUrl", json.getString("updateUrl"), "noticeUrl", json.getString("noticeUrl"), "notice", json.getString("notice"))); } } catch (Exception e) { e.printStackTrace(); } return new JsonResult(1, returnMap); }
Example 14
Source File: WebSocketAPI.java From zap-extensions with Apache License 2.0 | 4 votes |
@Override public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException { switch (name) { case ACTION_SEND_TEXT_MESSAGE: try { int channelId = params.getInt(PARAM_CHANNEL_ID); WebSocketProxy proxy = extension.getWebSocketProxy(channelId); if (proxy != null) { this.sendWebSocketMessage( proxy, params.getBoolean(PARAM_OUTGOING), params.getString(PARAM_MESSAGE)); } else { throw new ApiException( ApiException.Type.DOES_NOT_EXIST, "channelId: " + channelId); } } catch (IOException e) { LOG.warn(e.getMessage(), e); throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage()); } break; case ACTION_SET_BREAK_TEXT_MESSAGE: ExtensionBreak extBreak = Control.getSingleton() .getExtensionLoader() .getExtension(ExtensionBreak.class); if (extBreak == null) { throw new ApiException( ApiException.Type.INTERNAL_ERROR, "ExtensionBreak not present"); } Message msg = extBreak.getBreakpointManagementInterface().getMessage(); if (msg == null) { throw new ApiException( ApiException.Type.ILLEGAL_PARAMETER, "No currently intercepted message"); } else if (msg instanceof WebSocketMessageDTO) { WebSocketMessageDTO ws = (WebSocketMessageDTO) msg; ws.payload = params.optString(PARAM_MESSAGE, ""); extBreak.getBreakpointManagementInterface() .setMessage(ws, params.getBoolean(PARAM_OUTGOING)); } else { throw new ApiException( ApiException.Type.ILLEGAL_PARAMETER, "Intercepted message is not of the right type " + msg.getClass().getCanonicalName()); } break; default: throw new ApiException(ApiException.Type.BAD_ACTION); } return ApiResponseElement.OK; }
Example 15
Source File: PRReviewGHEventSubscriber.java From github-pr-comment-build-plugin with MIT License | 4 votes |
/** * Handles updates of pull requests. * @param event only PULL_REQUEST_REVIEW events * @param payload payload of gh-event. Never blank */ @Override protected void onEvent(GHEvent event, String payload) { JSONObject json = JSONObject.fromObject(payload); JSONObject pullRequest = json.getJSONObject("pull_request"); final String pullRequestUrl = pullRequest.getString("html_url"); Integer pullRequestId = pullRequest.getInt("number"); // Set some values used below final Pattern pullRequestJobNamePattern = Pattern.compile("^PR-" + pullRequestId + "\\b.*$", Pattern.CASE_INSENSITIVE); // Make sure the repository URL is valid String repoUrl = json.getJSONObject("repository").getString("html_url"); Matcher matcher = REPOSITORY_NAME_PATTERN.matcher(repoUrl); if (!matcher.matches()) { LOGGER.log(Level.WARNING, "Malformed repository URL {0}", repoUrl); return; } final GitHubRepositoryName changedRepository = GitHubRepositoryName.create(repoUrl); if (changedRepository == null) { LOGGER.log(Level.WARNING, "Malformed repository URL {0}", repoUrl); return; } LOGGER.log(Level.FINE, "Received review on PR {1} for {2}", new Object[] { pullRequestId, repoUrl }); ACL.impersonate(ACL.SYSTEM, new Runnable() { @Override public void run() { boolean jobFound = false; for (final SCMSourceOwner owner : SCMSourceOwners.all()) { for (SCMSource source : owner.getSCMSources()) { if (!(source instanceof GitHubSCMSource)) { continue; } GitHubSCMSource gitHubSCMSource = (GitHubSCMSource) source; if (gitHubSCMSource.getRepoOwner().equalsIgnoreCase(changedRepository.getUserName()) && gitHubSCMSource.getRepository().equalsIgnoreCase(changedRepository.getRepositoryName())) { for (Job<?, ?> job : owner.getAllJobs()) { if (pullRequestJobNamePattern.matcher(job.getName()).matches()) { if (!(job.getParent() instanceof MultiBranchProject)) { continue; } boolean propFound = false; for (BranchProperty prop : ((MultiBranchProject) job.getParent()).getProjectFactory(). getBranch(job).getProperties()) { if (!(prop instanceof TriggerPRReviewBranchProperty)) { continue; } propFound = true; ParameterizedJobMixIn.scheduleBuild2(job, 0, new CauseAction(new GitHubPullRequestReviewCause(pullRequestUrl))); break; } if (!propFound) { LOGGER.log(Level.FINE, "Job {0} for {1}:{2}/{3} does not have a trigger PR review branch property", new Object[] { job.getFullName(), changedRepository.getHost(), changedRepository.getUserName(), changedRepository.getRepositoryName() } ); } jobFound = true; } } } } } if (!jobFound) { LOGGER.log(Level.FINE, "PR review on {0}:{1}/{2} did not match any job", new Object[] { changedRepository.getHost(), changedRepository.getUserName(), changedRepository.getRepositoryName() } ); } } }); }
Example 16
Source File: PRUpdateGHEventSubscriber.java From github-pr-comment-build-plugin with MIT License | 4 votes |
/** * Handles updates of pull requests. * @param event only PULL_REQUEST events * @param payload payload of gh-event. Never blank */ @Override protected void onEvent(GHEvent event, String payload) { JSONObject json = JSONObject.fromObject(payload); // Since we receive both pull request and issue comment events in this same code, // we check first which one it is and set values from different fields JSONObject pullRequest = json.getJSONObject("pull_request"); final String pullRequestUrl = pullRequest.getString("html_url"); Integer pullRequestId = pullRequest.getInt("number"); // Make sure the action is edited String action = json.getString("action"); if (!ACTION_EDITED.equals(action)) { LOGGER.log(Level.FINER, "Pull request action is not edited ({0}) for PR {1}, ignoring", new Object[] { action, pullRequestUrl } ); return; } // Set some values used below final Pattern pullRequestJobNamePattern = Pattern.compile("^PR-" + pullRequestId + "\\b.*$", Pattern.CASE_INSENSITIVE); // Make sure the repository URL is valid String repoUrl = json.getJSONObject("repository").getString("html_url"); Matcher matcher = REPOSITORY_NAME_PATTERN.matcher(repoUrl); if (!matcher.matches()) { LOGGER.log(Level.WARNING, "Malformed repository URL {0}", repoUrl); return; } final GitHubRepositoryName changedRepository = GitHubRepositoryName.create(repoUrl); if (changedRepository == null) { LOGGER.log(Level.WARNING, "Malformed repository URL {0}", repoUrl); return; } LOGGER.log(Level.FINE, "Received update on PR {1} for {2}", new Object[] { pullRequestId, repoUrl }); ACL.impersonate(ACL.SYSTEM, new Runnable() { @Override public void run() { boolean jobFound = false; for (final SCMSourceOwner owner : SCMSourceOwners.all()) { for (SCMSource source : owner.getSCMSources()) { if (!(source instanceof GitHubSCMSource)) { continue; } GitHubSCMSource gitHubSCMSource = (GitHubSCMSource) source; if (gitHubSCMSource.getRepoOwner().equalsIgnoreCase(changedRepository.getUserName()) && gitHubSCMSource.getRepository().equalsIgnoreCase(changedRepository.getRepositoryName())) { for (Job<?, ?> job : owner.getAllJobs()) { if (pullRequestJobNamePattern.matcher(job.getName()).matches()) { if (!(job.getParent() instanceof MultiBranchProject)) { continue; } boolean propFound = false; for (BranchProperty prop : ((MultiBranchProject) job.getParent()).getProjectFactory(). getBranch(job).getProperties()) { if (!(prop instanceof TriggerPRUpdateBranchProperty)) { continue; } propFound = true; ParameterizedJobMixIn.scheduleBuild2(job, 0, new CauseAction(new GitHubPullRequestUpdateCause(pullRequestUrl))); break; } if (!propFound) { LOGGER.log(Level.FINE, "Job {0} for {1}:{2}/{3} does not have a trigger PR update branch property", new Object[] { job.getFullName(), changedRepository.getHost(), changedRepository.getUserName(), changedRepository.getRepositoryName() } ); } jobFound = true; } } } } } if (!jobFound) { LOGGER.log(Level.FINE, "PR update on {0}:{1}/{2} did not match any job", new Object[] { changedRepository.getHost(), changedRepository.getUserName(), changedRepository.getRepositoryName() } ); } } }); }
Example 17
Source File: WeixinGzuserController.java From jeewx-boot with Apache License 2.0 | 4 votes |
/** * @功能:粉丝同步 */ @ResponseBody @RequestMapping(value="syncFans",method = {RequestMethod.GET,RequestMethod.POST}) public AjaxJson syncFans(HttpServletResponse response,HttpServletRequest request) throws Exception{ AjaxJson j=new AjaxJson(); try { //update-begin-zhangweijian-----Date:20180807---for:线程移到controller中 //获取jwid final String jwid=request.getSession().getAttribute("jwid").toString(); String message=""; //获取token int total=0; String accessToken=WeiXinHttpUtil.getRedisWeixinToken(jwid); //调用一次测试微信接口以验证服务接口是否正常,并返回粉丝总数 if(StringUtils.isNotEmpty(accessToken)){ String requestUrl=user_List_url.replace("NEXT_OPENID", "").replace("ACCESS_TOKEN", accessToken); JSONObject jsonObj=WeixinUtil.httpRequest(requestUrl, "GET", ""); if(jsonObj==null){ message= "微信服务器访问异常,请稍候重试。"; //update-begin-zhangweijian-----Date:20180809---for:添加返回内容 j.setMsg(message); //update-end-zhangweijian-----Date:20180809---for:添加返回内容 return j; } if(!jsonObj.containsKey("errmsg")){ total = jsonObj.getInt("total"); }else{ //update-begin--Author:zhangweijian Date: 20180903 for:提示信息优化 String errcode=jsonObj.getString("errcode"); String msg = WxErrCodeUtil.testErrCode(errcode); j.setMsg("同步粉丝列表失败! "+msg); //update-end--Author:zhangweijian Date: 20180903 for:提示信息优化 return j; } } message="同步粉丝任务已启动,请稍候刷新。关注用户总数:"+total; //开启线程,同步粉丝数据 Thread t=new Thread(new Runnable() { @Override public void run() { weixinGzuserService.getFansListTask("0",jwid); MyJwWebJwid myJwWebJwid = myJwWebJwidService.queryByJwid(jwid); gzUserInfoTimer.batchInitAccountFensi(myJwWebJwid); } }); t.start(); //update-end-zhangweijian-----Date:20180807---for:线程移到controller中 j.setMsg(message); } catch (Exception e) { e.printStackTrace(); } return j; }
Example 18
Source File: ValidationServlet.java From WeChatEnterprise with Apache License 2.0 | 4 votes |
public void doGet(final HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); // type req.setAttribute("type", "validation"); // result String result = "1"; final String code = req.getParameter("code"); if (code != null) { System.out.println("validation start , code = " + code); // get access_token String access_token = WXApi.getAccessToken4Blocking(); System.out.println("validation start , access_token = " + access_token); if (access_token != null) { // get userid JSONObject userid_object = WXOAuth2.getCodeToUserId4Blocking( access_token, code); String userid = null; if (userid_object != null) { if (userid_object.has("UserId")) { userid = userid_object.getString("UserId"); } else { System.out .println("validation userid not exists , userid_object = " + userid_object.toString()); } } if (userid != null) { System.out.println("validation start , userid = " + userid); // get validation result JSONObject object = getValidationResult(access_token, userid); if(object!=null){ int errcode = object.getInt("errcode"); // validation success if (errcode == 0) { result = "0"; } // validation failed else{ // errcode req.setAttribute("errcode", errcode); } } } } } else { result = "1"; System.out.println("oauth2 failed , code = " + (code == null ? "null" : code)); } System.out.println(" "); System.out.println("*******************分割线************************"); System.out.println(" "); // result req.setAttribute("result", result); // 跳转到index.jsp req.getRequestDispatcher("index.jsp").forward(req, resp); }
Example 19
Source File: WxstoreUtils.java From jeewx-api with Apache License 2.0 | 4 votes |
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { logger.debug("*********HTTPREQUEST START********"); logger.debug("*********requestUrl is "+ requestUrl+" END AND requestMethod IS" +requestMethod + " END AND outputStr" +outputStr +" END ********"); JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url .openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) { httpUrlConn.connect(); } if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader( inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader( inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); if (jsonObject.containsKey("errcode") && jsonObject.getInt("errcode") != 0) { logger.debug("********* ERROR********{}",buffer.toString()); logger.debug("*********HTTPREQUEST END********"); throw new WexinReqException("httpRequest Method!errcode=" + jsonObject.getString("errcode") + ",errmsg = " + jsonObject.getString("errmsg")); } else { logger.debug("********* SUCCESS END********"); } } catch (ConnectException ce) { System.out.println("Weixin server connection timed out."); } catch (Exception e) { System.out.println("https request error:{}" + e.getMessage()); } return jsonObject; }
Example 20
Source File: WeixinGzuserServiceImpl.java From jeewx-boot with Apache License 2.0 | 4 votes |
@Override public String getFansListTask(String next_openid, String jwid) { //获取微信公众账号的关注粉丝(同步openid) String returnMsg; int total=0; try { returnMsg = "粉丝同步成功,同步粉丝条数:"; //获取token String accessToken=WeiXinHttpUtil.getRedisWeixinToken(jwid); if(StringUtils.isNotEmpty(accessToken)){ //多线程处理数据 ThreadPoolExecutor executor = new ThreadPoolExecutor(10,10,1,TimeUnit.SECONDS,new LinkedBlockingQueue()); List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>(2000); int k=0; //获取粉丝列表信息 String requestUrl=user_List_url.replace("NEXT_OPENID", "").replace("ACCESS_TOKEN", accessToken); while(oConvertUtils.isNotEmpty(next_openid) && k<2000){ k++; //调用接口获取粉丝列表(一次最多拉取10000) JSONObject jsonObj=WeixinUtil.httpRequest(requestUrl, "GET", ""); next_openid=null; //防止死循环 if(jsonObj==null){ continue; } if(!jsonObj.containsKey("errmsg")){ total = jsonObj.getInt("total"); int count=jsonObj.getInt("count"); if(count!=0){ //获取拉取的粉丝的openid JSONArray openIdArr = jsonObj.getJSONObject("data").getJSONArray("openid"); //将粉丝信息存到数据库 futures.add(executor.submit(new SyncFansInfo(jwid,openIdArr))); } next_openid = jsonObj.getString("next_openid"); //使用next_openid继续获取下一页粉丝数据[循环] //update-begin--Author:zhangweijian Date:20181015 for:同步粉丝问题 requestUrl=user_List_url.replace("ACCESS_TOKEN",accessToken).replace("NEXT_OPENID", next_openid); //update-end--Author:zhangweijian Date:20181015 for:同步粉丝问题 } } executor.shutdown(); //update-begin-zhangweijian-----Date:20180809---for:线程池结束判断 while (true) { if (executor.isTerminated()) { break; } Thread.sleep(200); } //update-end-zhangweijian-----Date:20180809---for:线程池结束判断 } } catch (Exception e) { e.printStackTrace(); } return "同步任务已启动,请稍候刷新。公众号粉丝总数:"+total; }