RestTemplate的get和post请求 以为https的请求自我笔记

今天在搞用开放的第三方api来做查询BTC USDT等操作

用到了resttemplate 但是usdt的搞了很久的403 但是用postman直接访问第三方可以

原来是因为resttemplate要升级一下 才能访问到https的请求

上代码

    //查询BTC的 get请求
    //https://mainnet.infura.io/YKZGQG2QTBx0tiWoB2IF
    //https://mainnet.infura.io/v3/17408bbb3d65465c8dfddba66d1733df
    @GetMapping("/queryBtc")
    @ResponseBody
    public String queryBtc(String address){
        String url = "https://api.blockcypher.com/v1/btc/main/addrs/"+address+"/balance";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        if (result ==null){
            return "";
        }
        JSONObject resultObj = JSONObject.parseObject(result);
        BigDecimal balance = new BigDecimal((Long) resultObj.get("balance")) ;
        return balance.divide(new BigDecimal(100000000)).toString();
    }
    //查询usdt的 此处用的是Post请求
    @GetMapping("/queryUsdt")
    @ResponseBody
    public String queryUsdt(String address)  {
        try {
            String url = "https://api.omniwallet.org/v2/address/addr/";
            RestTemplate restTemplate = this.restTemplate();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
            map.add("addr", address);
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
            ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class);
            String result = response.getBody();
            if (result ==null){
                return "";
            }
            JSONObject resultObj = JSONObject.parseObject(result);
            List<Map<String,Object>> balances = (List<Map<String, Object>>)JSONObject.parseObject(resultObj.get(address).toString()).get("balance");
            for ( Map<String,Object> item : balances ) {
                if ("SP31".equals(item.get("symbol"))){
                    return BigDecimal.valueOf(Long.valueOf(item.get("value").toString())).divide(new BigDecimal(100000000)).toString();
                }
            }
            return "";
        }catch (Exception e){
            logger.error(e.getMessage());
            return "";
        }
    }

    //对template的强化
    public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();

        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(csf)
                .build();

        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory();

        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        return restTemplate;
    }
    /**
     * 获取用户地址以太坊余额
     *
     * @param address
     * @return
     * @throws IOException
     */
    @ResponseBody
    @GetMapping("/queryEth")
    public BigDecimal getBalance(String address) throws IOException {
        Web3j web3j = Web3j.build(new HttpService("自己的eth节点 去web3j上申请"));
        EthGetBalance getBalance = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST).send();
        return Convert.fromWei(getBalance.getBalance().toString(), Convert.Unit.ETHER);
    }
    /**
     * 查询ETH下代币的余额
     * @param walletAddress
     * @return
     * @throws IOException
     */
    @GetMapping("/queryEthContract")
    @ResponseBody
    public BigDecimal balanceOfContractToken(String contractAddress, String walletAddress)  {
        Web3j web3j = Web3j.build(new HttpService("自己的节点地址,web3j上申请"));
        Function function = new Function("balanceOf",
                Arrays.<Type>asList(new Address(walletAddress)),
                Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {
                }));
        TransactionManager transactionManager = new TransactionManager(web3j, walletAddress) {
            @Override
            public EthSendTransaction sendTransaction(BigInteger gasPrice, BigInteger gasLimit, String to, String data, BigInteger value) throws IOException {
                return null;
            }
        };
        String encodedFunction = FunctionEncoder.encode(function);
        try {
            EthCall ethCall = web3j.ethCall(
                    org.web3j.protocol.core.methods.request.Transaction.createEthCallTransaction(
                            transactionManager.getFromAddress(), contractAddress, encodedFunction),
                    DefaultBlockParameterName.LATEST)
                    .send();
            String result = ethCall.getValue();
            if (StringUtils.isNotEmpty(result)) {
                if ("0x".equalsIgnoreCase(result) || result.length() == 2) {
                    result = "0x0";
                }
            }
            return (ethCall == null) ? null : new BigDecimal(CommonUtils.Hex2Decimal(result)).divide(new BigDecimal(1000000000000000000d));
        }catch (Exception e){
            logger.warn(e.getMessage());
        }

        return  null;

    }

下面这个是朋友提供给我的 没有试过

    /**
     * 查询代币余额
     *
     * @param address  账户地址
     * @param contract 合约地址
     * @return
     * @throws IOException
     */
    public BigDecimal getTokenBalance(String address, String contract) throws Exception {
        BigInteger balance = BigInteger.ZERO;
        Function fn = new Function("balanceOf", Collections.singletonList(new Address(address)), Collections.<TypeReference<?>>emptyList());
        String data = FunctionEncoder.encode(fn);
        Map<String, String> map = new HashMap<String, String>();
        map.put("to", contract);
        map.put("data", data);
        try {
            String methodName = "eth_call";
            Object[] params = new Object[]{map, "latest"};
            String result = jsonRpcHttpClient.invoke(methodName, params, Object.class).toString();
            if (StringUtils.isNotEmpty(result)) {
                if ("0x".equalsIgnoreCase(result) || result.length() == 2) {
                    result = "0x0";
                }
                balance = Numeric.decodeQuantity(result);
            }
        } catch (Throwable e) {
            throw new Exception("查询接口ERROR");
        }
        return new BigDecimal(balance);
    }

忘了加上工具类和pom了 哈哈

package com.example.demo;

import org.web3j.protocol.core.methods.response.TransactionReceipt;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * Created by y on 2018/3/7.
 */
public class CommonUtils {


    public static BigDecimal getSTAmount(String input) {
        if (input.startsWith("0x")) {
            input = input.replace("0x", "");
        }
        String hexAmount = input.substring(input.length() - 64, input.length());
        BigDecimal amount = new BigDecimal(new BigInteger(hexAmount, 16).toString());
        BigDecimal bigDecimal = amount.divide(new BigDecimal(1000000000000000000d));
        return bigDecimal;
    }

    public static String getContractAddressTo(String input) {
        if (input == null || "".equals(input) || input.length() != 138) return null;
        String addressTo = "";
        try {
            addressTo = "0x" + input.substring(34, input.length() - 64);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return addressTo;
    }


    public static BigDecimal bit18(BigInteger bigInteger) {
        BigDecimal amount = new BigDecimal(bigInteger);
        BigDecimal bigDecimal = amount.divide(new BigDecimal(1000000000000000000d));

        return bigDecimal;
    }

    /**
     * @param transactionReceipt
     * @return
     * @throws IOException
     */
    public static boolean verifyTransaction(TransactionReceipt transactionReceipt, BigInteger ethBlockNumber) throws IOException {
        String status = transactionReceipt.getStatus();
        boolean statusIsSuccess = "0x1".equals(status);
        boolean verifyTrain = ethBlockNumber.subtract(transactionReceipt.getBlockNumber()).compareTo(new BigInteger("12")) > 0;
        return statusIsSuccess && verifyTrain;
    }


    /**
     * @param x
     * @return
     */
    public static BigInteger Hex2Decimal(String x) {
        if (x.startsWith("0x")) {
            x = x.replace("0x", "");
        }
        return new BigInteger(x, 16);
    }

    /**
     * @param num
     * @return
     */
    public static String decimal2Hex(Long num) {
        if (num == null) return null;
        return Long.toHexString(num);


    }


}

    <dependency>
	    <groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>1.2.28</version>
	</dependency>
    <dependency>
		<groupId>org.web3j</groupId>
		<artifactId>core</artifactId>
		<version>3.5.0</version>
	</dependency>

猜你喜欢

转载自blog.csdn.net/sevenlxn/article/details/83149836