API接口调用模板(Get/Post)

TryHttpUtil

package com.inmyshow.util;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author ChangJiaNing
 * @Date 2022/12/20 19:54
 * @Describe
 **/
public class TryHttpUtil {

    private static Logger loggingStatistics = LoggerFactory.getLogger("statistics");

    public static String tryGet(String url) {

        return tryGet(url, 0, 10000);
    }

    public static String tryGet(String url, Integer timeOut) {

        return tryGet(url, 0, timeOut);
    }

    /**
     * @author ChangJiaNing
     * @date 2022/12/26 19:43
     * @Describe 返回JSON后toJSONString是为了判断返回结果是否是json,如果异常则重试10次
     **/

    private static String tryGet(String url, Integer count, Integer timeOut) {
        try {

            String res = HttpUtil.get(url, timeOut);

            loggingStatistics.info("url:{},调用第:{}次,返回结果:{}", url, count + 1, res);

            return JSON.parseObject(res).toJSONString();

        } catch (Exception e) {

            if (count != 9) {
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException ignored) {

                }

                loggingStatistics.info("调用 {} 接口,进行第 {} 次重试", url, count + 1);

                return tryGet(url, count + 1, timeOut);

            } else {

				ExceptionPrintUtil.exceptionPrint(e, StrUtil.format("调用接口:{}时,{}次全部异常", url, count + 1));

                if (e.getMessage().contains("Read timed out")) {
                    return StrUtil.EMPTY_JSON;
                }

                throw e;

            }
        }
    }

    public static String tryPost(String url,String body) {

        return tryPost(url,body, 0, 10000);
    }

    public static String tryPost(String url,String body,Integer count) {

        return tryPost(url,body, count, 10000);
    }

    public static String tryPost(String url,String body,Integer count,Integer timeOut){
        try{
            HttpRequest httpRequest = HttpUtil.createPost(url);
            httpRequest.body(body);
            HttpResponse execute = httpRequest.execute();
            String responseStr = execute.body();
            loggingStatistics.info("url:{},调用第:{}次,返回结果:{}", url, count + 1, responseStr);
            return JSON.parseObject(responseStr).toJSONString();
        }catch (Exception e){
            if(count != 9){
                try{
                    Thread.sleep(1000L);
                }catch (InterruptedException ignored){

                }
                loggingStatistics.info("调用 {} 接口,进行重试", url);

                return tryPost(url, body,count + 1, timeOut);
            }else {
                if (e.getMessage().contains("Read timed out")) {
                    return StrUtil.EMPTY_JSON;
                }
                ExceptionPrintUtil.exceptionPrint(e, StrUtil.format("调用接口:{}时,{}次全部异常", url, count + 1));
                throw e;
            }
        }
    }

}

TryGet Demo

	/**
	 * 抖音红人详情接口
	 */
	private void setVideoUserInfo() {

		try {
			String url = UrlBuilder.ofHttpWithoutEncode(systemConfig.getCommon().getAppUserInfoUrl())
					.addQuery("sec_user_id", douyinVideoInfoSpider.getSecUid())
					.toString();

			JSONObject resJsonObject = new JSONObject();

			int count = 1;

			while (true) {
				String res = TryHttpUtil.tryGet(url);
				if (StrUtil.EMPTY_JSON.equals(res)){
					break;
				}
				resJsonObject = JSON.parseObject(res);

				if (
						(!("200".equals(resJsonObject.getString("code")))) ||
								ObjectUtil.isNull(resJsonObject.getJSONObject("data")) ||
								ObjectUtil.isNull(resJsonObject.getJSONObject("data").getJSONObject("user"))
				) {
					if (count > 10) {
						break;
					}
					count++;
					continue;
				}

				JSONObject userJsonObject = resJsonObject.getJSONObject("data").getJSONObject("user");

				douyinVideoInfoSpider.setUserUrl("https://www.douyin.com/user/".concat(douyinVideoInfoSpider.getSecUid()));
				if (ObjectUtil.isNotNull(userJsonObject)) {
					douyinVideoInfoSpider.setNickName(userJsonObject.getString("nickname"));
					if (StrUtil.isNotBlank(userJsonObject.getString("unique_id"))) {
						douyinVideoInfoSpider.setDouyinAccount(userJsonObject.getString("unique_id"));
					} else {
						douyinVideoInfoSpider.setDouyinAccount(userJsonObject.getString("short_id"));
					}
					douyinVideoInfoSpider.setUserFansCount(userJsonObject.getString("mplatform_followers_count"));
					douyinVideoInfoSpider.setUserLikeCount(userJsonObject.getString("total_favorited"));
				}

				break;
			}

			recordTimer("抖音红人详情接口");
		} catch (Exception e) {
			String msg = ExceptionPrintUtil.exceptionPrint(e, "抖音红人详情接口");
			WeChatApiUtil.send(systemConfig.getCommon().getAlarmKey(), msg);
		}



	}

TryPost Demo

	/**
	 * 抖音app视频详情接口
	 */
	private void setAppVideoInfo() {

		try {
			String url = UrlBuilder.ofHttpWithoutEncode(systemConfig.getCommon().getAppVideoInfoUrl())
					.toString();

			JSONObject obj = new JSONObject();
			List<BigInteger> idList = new ArrayList<>();
			idList.add(new BigInteger(douyinVideoInfoSpider.getVideoId()));
			obj.put("origin", "datacenter");
			obj.put("aweme_ids", idList);

			JSONObject resJsonObject = new JSONObject();

			int count = 1;

			while (true) {

				String res = TryHttpUtil.tryPost(url, obj.toJSONString());
				if (StrUtil.EMPTY_JSON.equals(res)){
					break;
				}
				resJsonObject = JSON.parseObject(res);

				if (
						(!("200".equals(resJsonObject.getString("code")))) ||
								ObjectUtil.isNull(resJsonObject.getJSONObject("data")) ||
								ObjectUtil.isEmpty(resJsonObject.getJSONObject("data").getJSONArray("aweme_details"))
				) {
					if (count > 10) {
						break;
					}
					count++;
					continue;
				}

				JSONObject videoObj = resJsonObject.getJSONObject("data").getJSONArray("aweme_details").getJSONObject(0);

				/**
				 * 赋值
				 */
				douyinVideoInfoSpider.setTitle(videoObj.getJSONObject("share_info").getString("share_title"));
				Integer createTime = videoObj.getInteger("create_time");
				if (ObjectUtil.isNotNull(createTime)) {
					String formatCreateTime = DateUtil.format(new DateTime((long) createTime * 1000), "yyyy-MM-dd HH:mm:ss");
					douyinVideoInfoSpider.setPublishTime(formatCreateTime);
				}

				JSONObject statistics = videoObj.getJSONObject("statistics");
				if (ObjectUtil.isNotNull(statistics)) {
					douyinVideoInfoSpider.setCommentCount(statistics.getString("comment_count"));
					douyinVideoInfoSpider.setDiggCount(statistics.getString("digg_count"));
					douyinVideoInfoSpider.setShareCount(statistics.getString("share_count"));
					douyinVideoInfoSpider.setCollectCount(statistics.getString("collect_count"));
				}

				break;
			}

			recordTimer("抖音app视频详情实时接口");
		} catch (Exception e) {
			String msg = ExceptionPrintUtil.exceptionPrint(e, "抖音app视频详情实时接口");
			WeChatApiUtil.send(systemConfig.getCommon().getAlarmKey(), msg);
		}



	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值