地质所 沉降监测网建设项目
chenhuan
2024-05-16 0fdd42e318f51f9e3c6581473416af1cca69877f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.javaweb.third.baidu.baiduSite;
 
import com.javaweb.common.exception.BusinessException;
import com.javaweb.third.config.ThirdConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
 
import javax.net.ssl.HttpsURLConnection;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.Date;
 
/**
 * 百度站长推送工具类
 */
@Slf4j
public class BaiduPushUtil extends RestClientUtil {
    /**
     * 自行登录百度站长平台后获取响应的cookie
     */
 
    /**
     * 推送链接到百度站长平台
     *
     * @param urlString
     *         百度站长平台地址
     * @param params
     *         待推送的链接
     * @return api接口响应内容
     */
    public static String doPush(String urlString, String params) {
        if (StringUtils.isEmpty(ThirdConfig.getBaiduPushCookie())) {
            throw new BusinessException("尚未设置百度站长平台的Cookie信息,该功能不可用!");
        }
//        log.info("{} REST url: {}", new Date(), urlString);
        HttpURLConnection connection = null;
        try {
            connection = openConnection(urlString);
            connection.setRequestMethod("POST");
            // (如果不设此项,json数据 ,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            connection.setRequestProperty("Action", "1000");
            connection.setRequestProperty("User-Agent", USER_AGENT);
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Cookie", ThirdConfig.getBaiduPushCookie());
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 设置连接超时时间,单位毫秒
            connection.setConnectTimeout(10000);
            // 设置读取数据超时时间,单位毫秒
            connection.setReadTimeout(10000);
            // Post 请求不能使用缓存
            connection.setUseCaches(false);
            if (params != null) {
                final OutputStream outputStream = connection.getOutputStream();
                writeOutput(outputStream, params);
                outputStream.close();
            }
//            log.info("RestClientUtil response: {} : {}", connection.getResponseCode(), connection.getResponseMessage());
            if (connection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
                return readInput(connection.getInputStream(), "UTF-8");
            } else {
                return readInput(connection.getErrorStream(), "UTF-8");
            }
        } catch (Exception e) {
//            log.error("推送到百度站长平台发生异常!", e);
            return "";
        } finally {
            if (null != connection) {
                connection.disconnect();
            }
        }
    }
}