CsdnLikeServiceImpl.java 2.6 KB
Newer Older
1 2 3 4 5 6
package com.kwan.springbootkwan.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
7
import com.kwan.springbootkwan.entity.resp.LikeResponse;
8 9
import com.kwan.springbootkwan.service.CsdnLikeService;
import lombok.extern.slf4j.Slf4j;
10
import org.springframework.beans.factory.annotation.Value;
11 12 13 14 15 16
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class CsdnLikeServiceImpl implements CsdnLikeService {
17 18 19 20
    @Value("${csdn.cookie}")
    private String csdnCookie;
    @Value("${csdn.url.like_url}")
    private String url;
21 22 23 24
    /**
     * 点赞满了
     */
    private static boolean LIKE_IS_FULL = false;
25 26

    @Override
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    public Boolean isLike(String articleId, String userName) {
        if (LIKE_IS_FULL) {
            return true;
        }
        String url = "https://blog.csdn.net/" + userName + "/article/details/" + articleId;
        HttpResponse response = HttpUtil.createGet(url)
                .header("Cookie", csdnCookie)
                .form("articleId", articleId)
                .execute();
        final String body = response.body();
        if (body.contains("isLikeStatus = true")) {
            log.info("文章{}已经点过赞", articleId);
            return true;
        } else {
            log.info("文章{}未点过赞", articleId);
            return false;
        }
44
    }
45 46 47 48 49 50 51

    @Override
    public Boolean like(String articleId) {
        if (LIKE_IS_FULL) {
            return true;
        }
        HttpResponse response = HttpUtil.createPost(url)
52
                .header("Cookie", csdnCookie)
53 54 55 56 57
                .form("articleId", articleId)
                .execute();
        final String body = response.body();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
58 59
            final int code = objectMapper.readValue(body, LikeResponse.class).code;
            final LikeResponse.LikeDataDetail data = objectMapper.readValue(body, LikeResponse.class).getData();
60 61 62
            if (code == 200) {
                final boolean status = data.status;
                if (status) {
63
                    log.info("文章{}点赞成功", articleId);
64
                } else {
65
                    log.info("文章{}点赞取消", articleId);
66 67 68 69 70 71 72 73 74 75 76 77
                }
                return status;
            } else if (code == 400) {
                LIKE_IS_FULL = true;
                log.info("今日点赞次数已达上限!");
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return true;
    }
}