Java如何使用httpclient检测url状态及链接是否能打开

时间:2021-09-04 00:53:00

使用httpclient检测url状态及链接是否能打开

有时候我们需要检测某个url返回的状态码是不是200或者页面能不能正常打开响应可使用如下代码:

需要使用到的maven

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>
<dependency>
 <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.14</version>
</dependency>
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

代码:

?
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
public static String checkUrlConnection(String url) {
    // 创建http POST请求
    HttpGet httpGet = new HttpGet(url);
    httpGet.setHeader("Content-Type", "application/json");
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(600)// 设置连接主机服务超时时间
            .setConnectionRequestTimeout(1000)// 设置连接请求超时时间
            .setSocketTimeout(1000)// 设置读取数据连接超时时间
            .build();
    // 为httpPost实例设置配置
    httpGet.setConfig(requestConfig);
    // 设置请求头
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    int statusCode = 404;
    try {
        httpclient = HttpClients.createDefault();// 创建Httpclient对象
        response = httpclient.execute(httpGet);// 执行请求
        statusCode = response.getStatusLine().getStatusCode();
    }catch (SocketException e) {
        return "404";
    } catch (IOException e) {
        System.out.println("报错");
        return "404";
    }
    return String.valueOf(statusCode);
}

HTTPClient调用远程URL实例

案例描述

一次项目中后端服务需要从微信小程序获取扫码关注次数,网上搜各种示例都不太好用(代码冗余且效果不佳),于是自己花功夫做了一套。

?
1
2
3
4
5
public interface CustomerAppointAPIService {
    String getApiToken(JSONObject json);   
    JSONObject getFollowNum(JSONObject SaleId);
    void updateFacoriteCountRealitys();
}
?
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package com.faw.xxx.modules.staff.service.impl;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.faw.xxx.modules.staff.dao.DsCepStaffDAO;
import com.faw.xxx.modules.staff.entity.DsCepStaff;
import com.faw.xxx.modules.staff.service.CustomerAppointAPIService;
import com.faw.xxx.utils.SSLClient;
import cn.hutool.core.codec.Base64;
@Service
public class CustomerAppointAPIServiceImpl implements CustomerAppointAPIService {
    @Autowired
    private DsCepStaffDAO dsCepStaffDAO;
    /**
     * 授权接口
     * 参数格式:
     *{
     *  "Client":"digital_xxx",//客户端标识
     *  "Secret":"@-!xxx"//客户端接入秘钥
     *}
     */
    @Override
    public String getApiToken(JSONObject json) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String body = null;
        String postData = JSON.toJSONString(json);
        String encryptData=Base64.encode(postData);
        JSONObject params = new JSONObject();
        params.put("request", encryptData);
        String url = "https://miniappxxx.xxx.com.cn/api/v1/APIToken/GetApiToken";
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
//            httpPost.addHeader("Authorization", head);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(params.toJSONString(), "UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    body = EntityUtils.toString(resEntity,"utf-8");
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        JSONObject result = JSON.parseObject(body);
        JSONObject msgData = result.getJSONObject("msg");
        //接口直接返回token,以便于下一个接口调用
        return msgData.get("Token").toString();
    }
    /**
     * 微信小程序关注次数接口,POST请求
     */
    @Override
    public JSONObject getFollowNum(JSONObject SaleId) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String body = null;
        String postData = JSON.toJSONString(SaleId);
        String encryptData = Base64.encode(postData);
        JSONObject params = new JSONObject();
        params.put("request", encryptData);
        String json = "{\"Client\":\"digital_xxx\",\"Secret\":\"@-!6xxx\"}";
        String token = this.getApiToken(JSON.parseObject(json));
        String url = "https://miniappxxx.xxx.com.cn/api/v2/WechatApi/xxxNum";
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.addHeader("Authorization", "bearer " + token);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(params.toJSONString(), "UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    body = EntityUtils.toString(resEntity,"utf-8");
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        JSONObject result = JSON.parseObject(body);       
        JSONObject resultData = new JSONObject();
        resultData.put("code", result.get("code"));
        resultData.put("data", result.get("data"));     
        return resultData;
    }
    //更新所有在职销售顾问实际被关注数,此接口涉及内部代码,不做详解
    @Override
    @Transactional
    public void updateFacoriteCountRealitys() {
        //获取所有在职员工列表
        List<DsCepStaff> dsCepStaffs = dsCepStaffDAO.getAllOnPost();
        if (dsCepStaffs.size()>0) {
            for (DsCepStaff dsCepStaff : dsCepStaffs) {
                //更新销售顾问实际被关注数
                JSONObject SaleId = new JSONObject();
                SaleId.put("SaleId", dsCepStaff.getStaffId());
                JSONObject resultData = this.getFollowNum(SaleId);
                if (resultData != null) {
                    
                    Integer facoriteCountReality = Integer.parseInt(resultData.get("data").toString());
                    dsCepStaffDAO.updateFacoriteCountRealityByStaffId(facoriteCountReality, dsCepStaff.getStaffId());
                }
            }
        }
    }  
}
?
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
package com.faw.xxx.utils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
 * 用于进行Https请求的HttpClient
 * @author user
 *
 */
public class SSLClient extends DefaultHttpClient {
    public SSLClient() throws Exception{
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_33697094/article/details/119870749