How to Use apache. httpcomponents,
For http use of the get method, note the splicing of URIBuilder.
private static final String URL_LIVE = "https://apilayer.net/api/live"; private static final String URL_HISTORICAL = "https://apilayer.net/api/historical"; private static final String SOURCE = "USD"; private static final String CURRENCIES = "CNY"; @Value("${custom.currencylayer.access-key}") private String accessKey; private final ExchangeRateRepository exchangeRateRepository; private final RedisTemplate
redisTemplate; public ExchangeRateServiceImpl(ExchangeRateRepository exchangeRateRepository, RedisTemplate
redisTemplate) { this.exchangeRateRepository = exchangeRateRepository; this.redisTemplate = redisTemplate; } protected JSONObject fetchAndParseExchangeRate(LocalDate date) throws FetchExchangeRateException { String result; try { URI uri; if (Objects.isNull(date)) { uri = new URIBuilder(URL_LIVE) .addParameter("access_key", accessKey) .addParameter("source", SOURCE) .addParameter("currencies", CURRENCIES) .build(); } else { uri = new URIBuilder(URL_HISTORICAL) .addParameter("access_key", accessKey) .addParameter("source", SOURCE) .addParameter("currencies", CURRENCIES) .addParameter("date", date.toString()) .build(); } result = Request.Get(uri).execute().returnContent().asString(); } catch (URISyntaxException | IOException e) { throw new FetchExchangeRateException(e); } JSONObject object = JSONObject.parseObject(result); if (!object.getBoolean("success")) { String message = String.format("Failed to fetch and parse exchange rate, date: %s", date); LOGGER.warn(">>> ExchangeRate result: {}", object.toJSONString()); throw new FetchExchangeRateException(message); } return object; }
For the http usage of the POST method, note the splicing of URIBuilder.
private static final String URL_SYN_DATA = "https://baseservice.test.joel.com/datasync/apps/"; public String exe(String appId) { URI uri; String result; String retureVal = ""; try { uri = new URIBuilder(URL_SYN_DATA+appId).build(); result = Request.Post(uri).execute().returnContent().asString(); JSONObject jsonObject = JSONObject.parseObject(result); String success = jsonObject.getString("success"); String appId1 = jsonObject.getString("appId"); retureVal = success; } catch (URISyntaxException | IOException e) { e.printStackTrace(); retureVal="catchError"; } return retureVal; }
The following dependencies are used:
org.apache.httpcomponents
fluent-hc
com.alibaba
fastjson