com.alibaba.fastjson.JSON Java Examples

The following examples show how to use com.alibaba.fastjson.JSON. 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: AppDemoController.java    From Shop-for-JavaWeb with MIT License 7 votes vote down vote up
/**
 * 级联选择数据
 */
@RequestMapping("/ajax-select-chained")
public void ajaxAdd(HttpServletResponse response) throws IOException {
	boolean result = false;
	String message = "";
	Map<String, String> data = Maps.newHashMap();
	data.put("", "--");
	data.put("series-1", "1 series");
	data.put("series-2", "2 series");
	data.put("series-3", "3 series");
	data.put("series-4", "4 series");
	data.put("selected", "series-3");

	JsonUtils.setResponse(response);
	response.getWriter().print(JSON.toJSONString(data));
}
 
Example #2
Source File: UploadConfiguration.java    From spring-cloud-shop with MIT License 7 votes vote down vote up
static String uploadStream(InputStream is, String fileName) {
    UploadManager uploadManager = UploadConfiguration.getUploadManager();
    try {

        String key = SysConfigMap.get(SysConfigKeys.QINIU_BUCKET) + '/' + DateUtils.format(LocalDateTime.now(), DateUtils.NORM_DATE_PATTERN) + "/" + fileName;
        Response response = uploadManager.put(is, key, UploadConfiguration.getToken(), null, null);
        if (response.isOK()) {
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return putRet.key;
        }

    } catch (QiniuException e) {
        throw new RuntimeException("上传文件失败");
    }
    return null;
}
 
Example #3
Source File: HoubiProUtil.java    From GOAi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 解析单个精度
 * @param result 请求结果
 * @param symbol 解析币对
 * @return 精度
 */
public static Precision parsePrecision(String result, String symbol) {
    JSONObject r = JSON.parseObject(result);
    if (OK.equals(r.getString(STATUS))) {
        JSONArray data = r.getJSONArray(DATA);
        for (int i = 0; i < data.size(); i++) {
            JSONObject t = data.getJSONObject(i);
            if (symbol.equalsIgnoreCase(t.getString("symbol"))) {

                symbol = t.getString("base-currency") + "_" + t.getString("quote-currency");
                symbol = symbol.toUpperCase();
                Integer base = t.getInteger("amount-precision");
                Integer count = t.getInteger("price-precision");

                return new Precision(data.getString(i), symbol,
                        base, count,
                        null, null,
                        null, null,
                        null, null);
            }
        }
    }
    return null;
}
 
Example #4
Source File: TieBaApi.java    From tieba-api with MIT License 6 votes vote down vote up
/**
 * 查询是否关注某个贴吧
 * @param tbName 贴吧名称
 * @param bduss bduss
 * @return true or false
 */
public Boolean isFocus(String tbName, String bduss) {
	HttpKit hk = HttpKit.getInstance();
	Boolean flag = false;
	try {
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("BDUSS", bduss));
		list.add(new BasicNameValuePair("fid", api.getFid(tbName)));
		list.add(new BasicNameValuePair("kw", tbName));
		list.add(new BasicNameValuePair("tbs", api.getTbs(bduss)));
		list.add(new BasicNameValuePair("sign", StrKit.md5Sign(list)));
		HttpResponse response = hk.execute(Constants.LIKE_TIEBA_URL, null, list);
		String fr = EntityUtils.toString(response.getEntity());
		Integer isLike = (Integer)JSONPath.eval(JSON.parse(fr), "$.info.is_like");
		if(isLike == 1) {
			flag = true;
		}
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
	}
	if(flag == false) {
		//查询结果后如果未关注,需要取消关注
		this.unfocus(bduss, tbName);
	}
	return flag;
}
 
Example #5
Source File: RestExceptionHandler.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
    HttpServletResponse httpServletResponse, Object o, Exception e) {
  LOGGER.error("rest error:", e);
  ModelAndView modelAndView = new ModelAndView();
  try {
    ResultInfo resultInfo = new ResultInfo().setStatus(ResultStatus.ERROR.getCode())
        .setMsg(ResultInfo.MSG_ERROR);
    Map<String, Object> attr = JSON.parseObject(JSON.toJSONString(resultInfo), Map.class);
    MappingJackson2JsonView view = new MappingJackson2JsonView();
    view.setAttributesMap(attr);
    modelAndView.setView(view);
  } catch (Exception e1) {
    e1.printStackTrace();
  }
  return modelAndView;
}
 
Example #6
Source File: MchNotifyController.java    From xxpay-master with MIT License 6 votes vote down vote up
@RequestMapping("/list")
@ResponseBody
public String list(@ModelAttribute MchNotify mchNotify, Integer pageIndex, Integer pageSize) {
    PageModel pageModel = new PageModel();
    int count = mchNotifyService.count(mchNotify);
    if(count <= 0) return JSON.toJSONString(pageModel);
    List<MchNotify> mchNotifyList = mchNotifyService.getMchNotifyList((pageIndex-1)*pageSize, pageSize, mchNotify);
    if(!CollectionUtils.isEmpty(mchNotifyList)) {
        JSONArray array = new JSONArray();
        for(MchNotify po : mchNotifyList) {
            JSONObject object = (JSONObject) JSONObject.toJSON(po);
            if(po.getCreateTime() != null) object.put("createTime", DateUtil.date2Str(po.getCreateTime()));
            if(po.getLastNotifyTime() != null) object.put("lastNotifyTime", DateUtil.date2Str(po.getLastNotifyTime()));
            array.add(object);
        }
        pageModel.setList(array);
    }
    pageModel.setCount(count);
    pageModel.setMsg("ok");
    pageModel.setRel(true);
    return JSON.toJSONString(pageModel);
}
 
Example #7
Source File: SimplePersonnelAuthenticationBuilderTest.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    JSONObject auth = new JSONObject();
    auth.put("personnel", Maps.buildMap()
            .put("id", "1234")
            .put("name", "234")
            .get());

    auth.put("orgIds", JSON.parseArray("[{\"value\":\"123\",\"children\":[{\"value\":\"234\"}]}]"));

    auth.put("positions", JSON.parseArray("[{\"id\":\"1234\"," +
            "\"department\":{\"id\":\"1234\",\"org\":{\"id\":\"234\",\"district\":{\"id\":\"test\"}}}}]"));

    SimplePersonnelAuthentication authorization = fromJson(auth.toJSONString());


    Object json = JSON.toJSON(authorization);
    System.out.println(JSON.toJSONString(json, SerializerFeature.PrettyFormat));

    System.out.println(JSON.toJSONString(FastBeanCopier.copy(authorization,new JSONObject())).equals(json.toString()));
}
 
Example #8
Source File: BoardModel.java    From NGA-CLIENT-VER-OPEN-SOURCE with GNU General Public License v2.0 6 votes vote down vote up
private List<BoardCategory> loadPreloadBoards() {
    String categoryJson = StringUtils.getStringFromAssets("json/category_old.json");
    List<BoardBean> beans = JSON.parseArray(categoryJson, BoardBean.class);
    List<BoardCategory> categories = new ArrayList<>();
    for (BoardBean categoryBean : beans) {

        BoardCategory category = new BoardCategory(categoryBean.name);
        for (BoardBean.ContentBean contentBean : categoryBean.content) {
            if (TextUtils.isEmpty(contentBean.nameS)) {
                category.addBoard(new Board(contentBean.fid, contentBean.stid, contentBean.name));
            } else {
                category.addBoard(new Board(contentBean.fid, contentBean.stid, contentBean.nameS));
            }
        }
        categories.add(category);
    }
    return categories;
}
 
Example #9
Source File: ClientInvoker.java    From dubbo-plus with Apache License 2.0 6 votes vote down vote up
@Test
public void invokeSayHello(){
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://localhost:8080/net.dubboclub.restful.api.FirstRestfulService1/sayHello/1.0.1/all");
    Map<String,String> requestEntity = new HashMap<String,String>();
    requestEntity.put("arg1","Bieber");
    HttpEntity httpEntity = new ByteArrayEntity(JSON.toJSONBytes(requestEntity));
    httpPost.setEntity(httpEntity);
    try {
        CloseableHttpResponse response =  httpclient.execute(httpPost);
        System.out.println(response.getStatusLine());
        HttpEntity entity2 = response.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        System.out.println(EntityUtils.toString(entity2));
        response.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #10
Source File: PictureServiceImpl.java    From eladmin with Apache License 2.0 6 votes vote down vote up
@Override
public void synchronize() {
    //链式构建请求
    String result = HttpRequest.get(ElAdminConstant.Url.SM_MS_URL + "/v2/upload_history")
            //头信息,多个头信息多次调用此方法即可
            .header("Authorization", token)
            .timeout(20000)
            .execute().body();
    JSONObject jsonObject = JSONUtil.parseObj(result);
    List<Picture> pictures = JSON.parseArray(jsonObject.get("data").toString(), Picture.class);
    for (Picture picture : pictures) {
        if(!pictureRepository.existsByUrl(picture.getUrl())){
            picture.setSize(FileUtil.getSize(Integer.parseInt(picture.getSize())));
            picture.setUsername("System Sync");
            picture.setMd5Code(null);
            pictureRepository.save(picture);
        }
    }
}
 
Example #11
Source File: JsonTest.java    From MeetingFilm with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    String randomKey = "1xm7hw";

    BaseTransferEntity baseTransferEntity = new BaseTransferEntity();
    SimpleObject simpleObject = new SimpleObject();
    simpleObject.setUser("fsn");
    baseTransferEntity.setObject("123123");

    String json = JSON.toJSONString(simpleObject);

    //md5签名
    String encrypt = MD5Util.encrypt(json + randomKey);
    baseTransferEntity.setSign(encrypt);

    System.out.println(JSON.toJSONString(baseTransferEntity));
}
 
Example #12
Source File: JsonRequestTest.java    From Okra with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void methodMap() throws Exception {
    JsonRequest request = new JsonRequest();
    request.setRid(1);
    ServiceManager manager = AppContext.getBean(ServiceManager.class);
    manager.registerService(new DemoComponent());
    //  list
    request.setData(JSON.toJSONString(new HashMap<Integer, Integer>() {{
        put(1, 1);
        put(2, 2);
    }}));
    manager.getCommand("methodMapBase").execute(null, request);
    //  list
    request.setData(JSON.toJSONString(new HashMap<Integer, VoObj>() {{
        put(1, new VoObj(100));
        put(2, new VoObj(101));
    }}));
    manager.getCommand("methodMapObject").execute(null, request);
}
 
Example #13
Source File: LowLevelRestController.java    From ProjectStudy with MIT License 6 votes vote down vote up
/**
 * 同步执行HTTP请求
 *
 * @param
 * @return org.springframework.http.ResponseEntity<java.lang.String>
 * @throws IOException
 * @author wliduo[[email protected]]
 * @date 2019/8/8 17:15
 */
@GetMapping("/es")
public ResponseBean getEsInfo() throws IOException {
    Request request = new Request("GET", "/");
    // performRequest是同步的,将阻塞调用线程并在请求成功时返回Response,如果失败则抛出异常
    Response response = restClient.performRequest(request);
    // 获取请求行
    RequestLine requestLine = response.getRequestLine();
    // 获取host
    HttpHost host = response.getHost();
    // 获取状态码
    int statusCode = response.getStatusLine().getStatusCode();
    // 获取响应头
    Header[] headers = response.getHeaders();
    // 获取响应体
    String responseBody = EntityUtils.toString(response.getEntity());
    return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody));
}
 
Example #14
Source File: UserControllerTest.java    From AthenaServing with Apache License 2.0 6 votes vote down vote up
/**
 * 新增用户
 *
 * @throws Exception
 */
@Test
public void test_user_3_add() throws Exception {
    AddUserRequestBody body = new AddUserRequestBody();
    body.setAccount("sctang");
    body.setEmail("[email protected]");
    body.setPhone("13739263609");
    body.setUserName("sctang");
    String result = this.mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/user/add")
            .content(JSON.toJSONString(body))
            .contentType(MediaType.APPLICATION_JSON)
            .session((MockHttpSession) Utils.getLoginSession(this.mockMvc))
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn().getResponse().getContentAsString();
    Utils.assertResult(result);
}
 
Example #15
Source File: ClientTest.java    From message_interface with MIT License 6 votes vote down vote up
@Test(priority = 1)
public void testApplyStaff() throws IOException {
    ApplyStaffInfo info = new ApplyStaffInfo();
    info.setFromPage("http://163.com");
    info.setFromTitle("网易首页");
    info.setUid(foreignId);
    info.setProductId("com.163");
    info.setDeviceType("Web#Windows#10#Chrome");
    info.setStaffType(1);

    ApplyStaffResult result = client.applyStaff(info);
    if (result.getCode() == 200 && result.getSession().getStaffType() == 1) {
        sessionId = result.getSession().getSessionId();
    }

    out("applyStaff", JSON.toJSONString(result));
}
 
Example #16
Source File: ConfigUtil.java    From Spring-generator with MIT License 6 votes vote down vote up
/**
 * 获得SqlAndParams配置文件信息
 * 
 * @return
 * @throws Exception
 */
public static CustomPropertyConfig getCustomPropertyConfig(String name) throws Exception {
	Connection conn = null;
	Statement stat = null;
	ResultSet rs = null;
	try {
		conn = getConnection();
		stat = conn.createStatement();
		String sql = String.format("select * from CustomPropertyConfig where name='%s'", name);
		ResultSet resultSet = stat.executeQuery(sql);
		while (resultSet.next()) {
			CustomPropertyConfig result = JSON.parseObject(resultSet.getString("value"), CustomPropertyConfig.class);
			return result;
		}
	} finally {
		if (rs != null)
			rs.close();
		if (stat != null)
			stat.close();
		if (conn != null)
			conn.close();
	}
	return null;
}
 
Example #17
Source File: ChainRelativeTest.java    From sagacity-sqltoy with Apache License 2.0 6 votes vote down vote up
@Test
public void testRowsChainRelative() {
	// |月份 | 产品 |交易笔数 | 环比 | 金额 | 环比 | 收入 | 环比 |
	// | 5月 | 香蕉 | 2000 | 环比 | 金额 | 环比 | 收入 | 环比 |
	// | 5月 | 苹果 | 2000 | 环比 | 金额 | 环比 | 收入 | 环比 |
	// | 4月 | 香蕉 | 2000 | 环比 | 金额 | 环比 | 收入 | 环比 |0
	// | 4月 | 苹果 | 2000 | 环比 | 金额 | 环比 | 收入 | 环比 |1
	// | 3月 | 香蕉 | 2000 | 环比 | 金额 | 环比 | 收入 | 环比 |
	// | 3月 | 苹果 | 2000 | 环比 | 金额 | 环比 | 收入 | 环比 |
	Object[][] values = { { "5月", "香蕉", 2000 }, { "5月", "苹果", 1900 }, { "4月", "香蕉", 1800 }, { "4月", "苹果", 1800 },
			{ "3月", "香蕉", 1600 }, { "3月", "苹果", 1700 } };
	List result = CollectionUtil.arrayToDeepList(values);
	RowsChainRelativeModel rowsRelative = new RowsChainRelativeModel();
	rowsRelative.setGroupColumn("1");
	rowsRelative.setReduceOne(false);
	rowsRelative.setRelativeColumns(new String[] { "2" });
	rowsRelative.setFormat("#.00%");
	rowsRelative.setReverse(true);
	HashMap<String, Integer> labelIndexMap = new HashMap<String, Integer>();
	RowsChainRelative.process(rowsRelative, labelIndexMap, result);
	for (int i = 0; i < result.size(); i++) {
		System.out.println(JSON.toJSONString(result.get(i)));
	}
}
 
Example #18
Source File: NotifyUtil.java    From java-unified-sdk with Apache License 2.0 6 votes vote down vote up
private static Set<String> getRegisteredApps() {
  if (AVOSCloud.applicationContext == null) {
    return null;
  }
  File registerFile = getRegisterAppsFile();
  Set<String> appSet = new HashSet<String>();
  if (registerFile.exists()) {
    String registerApps = AVPersistenceUtils.sharedInstance().readContentFromFile(registerFile);
    if (!StringUtil.isEmpty(registerApps)) {
      // catch parse Exception
      try {
        appSet.addAll(JSON.parseObject(registerApps, Set.class));
      } catch (Exception e) {
        if (AVOSCloud.showInternalDebugLog()) {
          Log.e(TAG, "getRegisteredApps", e);
        }
      }
      return appSet;
    }
  }
  return appSet;
}
 
Example #19
Source File: OkHttpTracerTest.java    From sofa-tracer with Apache License 2.0 6 votes vote down vote up
private void testOkHttpPost() throws Exception {
    PostBody postBody = new PostBody();
    postBody.setAge(111);
    postBody.setFemale(false);
    postBody.setName("guanchao.ygc/xuelian");
    String httpGetUrl = urlHttpPrefix + "/httpclient";
    //baggage
    SofaTracer sofaTracer = OkHttpTracer.getOkHttpTracerSingleton().getSofaTracer();
    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
    SofaTracerSpan sofaTracerSpan = (SofaTracerSpan) sofaTracer.buildSpan(
        "HttpClientTracer Baggage").start();
    sofaTracerSpan.setBaggageItem("key1", "baggage1");
    sofaTracerSpan.setBaggageItem("key2", "baggage2");
    sofaTraceContext.push(sofaTracerSpan);

    String responseStr = new OkHttpClientInstance().executePost(httpGetUrl,
        JSON.toJSONString(postBody));
    PostBody resultPostBody = JSON.parseObject(responseStr, PostBody.class);
    assertEquals(postBody, resultPostBody);
}
 
Example #20
Source File: AllinPayGatewayServiceImpl.java    From aaden-pay with Apache License 2.0 5 votes vote down vote up
@Override
public ThirdPayResponse netsave(ThirdPayRecord tr) {
	Map<String, String> postMap = adaptor.builderPostMap(tr);
	logger.info("通联网银请求报文:" + JSON.toJSONString(postMap));
	ThirdPayResponse resp = new ThirdPayResponse();
	resp.setPostUrl(adaptor.getUrl());
	resp.setPostMap(postMap);
	resp.setSendStatus(SendStatus.SENDING);
	return resp;
}
 
Example #21
Source File: CcImageUploadService.java    From imagehosting with MIT License 5 votes vote down vote up
@Override
String anaysisResult(String response) {
	try {
		return "https://upload.cc/"
				+ JSON.parseObject(response).getJSONArray("success_image").getJSONObject(0).getString("url");
	} catch (Exception e) {
		// ignore
	}
	return null;
}
 
Example #22
Source File: HessianTest.java    From MyTv with Apache License 2.0 5 votes vote down vote up
/**
 * 测试电视台
 */
public void testEpgStation() {
	HessianProxyFactory proxy = new HessianProxyFactory();
	try {
		JolynnTv tv = (JolynnTv) proxy.create(JolynnTv.class, url);
		String stations = tv.getMyTvByClassify("番禺有线");
		JSONArray array = JSON.parseArray(stations);
		assertNotNull(array);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #23
Source File: LeadershipTransferCommand.java    From openmessaging-storage-dledger with Apache License 2.0 5 votes vote down vote up
@Override
public void doCommand() {
    DLedgerClient dLedgerClient = new DLedgerClient(group, peers);
    dLedgerClient.startup();
    LeadershipTransferResponse response = dLedgerClient.leadershipTransfer(leaderId, transfereeId, term);
    logger.info("LeadershipTransfer code={}, Result:{}", DLedgerResponseCode.valueOf(response.getCode()),
        JSON.toJSONString(response));
    dLedgerClient.shutdown();
}
 
Example #24
Source File: TomcatReadonlyComponentImpl.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
@Override
public ResultMap putJson(final String key) {
    try {
        final Map<String, String[]> map = ReadStream.read(new TypeReference<Map<String, String[]>>() { });
        Assert.notEmpty(map);
        final String[] strArr = map.get("value");
        Assert.notEmpty(strArr);
        Assert.isTrue(strArr.length == 3);
        return ResultMap.create(key + '=' + JSON.toJSONString(strArr), HttpStatus.OK);
    } catch (final Throwable e) {
        return ResultMap.create(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
 
Example #25
Source File: FastJson2JsonRedisSerializer.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] serialize(T t) throws SerializationException {
    if (t == null) {
        return new byte[0];
    }
    return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
 
Example #26
Source File: Test4.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
private void testFastJson(Order[] order) {
    String str = JSON.toJSONString(order);
    System.out.println(str);

    System.out.println(MyStringUtils.center(80, "*"));


    List<Order> order1 = JSON.parseArray(str, Order.class);
    for (Order or : order1)
        System.out.println(or.getProperty() + "," + or.getDirection());
}
 
Example #27
Source File: SimpleHintParser.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
private static ExtraCmdRouteCondition decodeExtra(JSONObject jsonObject) throws JSONException {
    ExtraCmdRouteCondition rc = new ExtraCmdRouteCondition();
    String extraCmd = containsKvNotBlank(jsonObject, EXTRACMD);
    if (StringUtils.isNotEmpty(extraCmd)) {
        JSONObject extraCmds = JSON.parseObject(extraCmd);
        for (Map.Entry<String, Object> entry : extraCmds.entrySet()) {
            rc.getExtraCmds().put(StringUtils.upperCase(entry.getKey()), entry.getValue());
        }
    }
    return rc;
}
 
Example #28
Source File: MainAgent.java    From COLA with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static AgentArgs convert(String agentArgs){
    JSONObject jsonObject = JSON.parseObject(agentArgs);
    AgentArgs model = new AgentArgs();
    model.setClassName(jsonObject.getString("className"));
    model.setMethodName(jsonObject.getString("methodName"));
    model.setTranslateType(TranslateType.valueOf(jsonObject.getString("translateType")));
    return model;
}
 
Example #29
Source File: HuobiProExchange.java    From GOAi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
     * 下单
     * @param info 请求信息
     * @param delay 延时
     * @param price 价格
     * @param amount 数量
     * @param type 类型
     * @return 请求信息
     */
    private List<MimeRequest> place(ExchangeInfo info, long delay,
                                    String price, String amount, String type) {
        String symbol = this.symbol(info);
        String access = info.getAccess();
        String secret = info.getSecret();

        String accountId = this.getAccountId(access, secret);
        Parameter parameter = this.addParam(access, delay);
        String sign = this.sign(secret, "POST", site, apiPlace, parameter);
        parameter.add("Signature", encode(sign));
        Parameter param = Parameter.build()
                .add("account-id", accountId)
                .add("amount", amount)
                .add("source", "api")
                .add("symbol", symbol)
                .add("type", type);
        if (useful(price)) {
            param.add("price", price);
        }
        MimeRequest request = new MimeRequest.Builder()
                .url(address + apiPlace + "?" + parameter.concat())
                .post()
                .header("Accept-Language", "zh-CN")
//                .header("Content-Type", "application/json;charset=UTF-8")
                .body(param.json(JSON::toJSONString))
                .build();
        return Collections.singletonList(request);
    }
 
Example #30
Source File: WeixinHelper.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * 获取微信的access_token
 * @see 默认修饰符default即只有同包中的类才可使用
 * @see {"access_token":"8DF72J-d_u3XIaq22e_HUY_fe5wfdoj6awnq2wDrk5v05zf1yEuUhUdtfX7yqB5wAJ1edwGrgAyJvinZTXl2RamjsqDOIg4L1humLuj32Oo","expires_in":7200}
 * @see {"errcode":40125,"errmsg":"invalid appsecret, view more at http:\/\/t.cn\/RAEkdVq hint: [M5_jKa0125vr22]"}
 * @return 获取失败时将抛出Exception
 */
static String getWeixinAccessToken(String appid, String appsecret) throws IllegalAccessException {
    String reqURL = WeixinConstants.URL_WEIXIN_GET_ACCESSTOKEN.replace(WeixinConstants.URL_PLACEHOLDER_APPID, appid).replace(WeixinConstants.URL_PLACEHOLDER_APPSECRET, appsecret);
    String respData = HTTPUtil.post(reqURL, null, null);
    LogUtil.getLogger().info("获取微信access_token,微信应答报文为-->{}", respData);
    Map<String, String> map = JSON.parseObject(respData, new TypeReference<Map<String, String>>(){});
    if(respData.contains("access_token")){
        return map.get("access_token");
    }
    String errmsg = WeixinCodeEnum.getMsgByCode(Integer.parseInt((map.get("errcode"))));
    if(StringUtils.isBlank(errmsg)){
        errmsg = map.get("errmsg");
    }
    throw new IllegalAccessException(errmsg);
}