How does Java use httpclient to detect the status of url and whether the link can be opened

  • 2021-11-14 05:56:49
  • OfStack

Directory uses httpclient to detect url status and whether the link can be opened. mavenHTTPClient needs to be used to call remote URL instance case description

Use httpclient to detect url status and whether the link can be opened

Sometimes we need to check whether the status code returned by an url is 200 or whether the page can open normally. The response can use the following code:

maven to be used


<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>

Code:


    public static String checkUrlConnection(String url) {
        //  Create http POST Request 
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json");
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(600)//  Set the connection host service timeout 
                .setConnectionRequestTimeout(1000)//  Set the connection request timeout 
                .setSocketTimeout(1000)//  Set the read data connection timeout 
                .build();
        //  For httpPost Instance Setting Configuration 
        httpGet.setConfig(requestConfig);
        //  Set the request header 
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        int statusCode = 404;
        try {
            httpclient = HttpClients.createDefault();//  Create Httpclient Object 
            response = httpclient.execute(httpGet);//  Execute request 
            statusCode = response.getStatusLine().getStatusCode();
        }catch (SocketException e) {
            return "404";
        } catch (IOException e) {
            System.out.println(" Report an error ");
            return "404";
        }
        return String.valueOf(statusCode);
    }

HTTPClient calls a remote URL instance

Case description

In a project, the back-end service needs to get the number of code scanning attention from WeChat applet, and it is not easy to search various examples online (the code is redundant and the effect is not good), so I made one set by myself.


public interface CustomerAppointAPIService {
	String getApiToken(JSONObject json);	
	JSONObject getFollowNum(JSONObject SaleId);
	void updateFacoriteCountRealitys();
}

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;
	/**
	 *  Authorization interface 
	 *  Parameter format: 
	 *{
	 *	"Client":"digital_xxx",// Client ID 
	 *	"Secret":"@-!xxx"// Client access key 
	 *}
	 */
	@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");
        // Interface returns directly token In order to facilitate the following 1 Interface calls 
        return msgData.get("Token").toString();
	}
	/**
	 *  WeChat applet attention times interface ,POST Request  
	 */
	@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;
	}
	// Update the actual number of attention paid to all in-service sales consultants. This interface involves internal code and does not explain in detail 
	@Override
	@Transactional
	public void updateFacoriteCountRealitys() {
		// Get a list of all active employees 
		List<DsCepStaff> dsCepStaffs = dsCepStaffDAO.getAllOnPost();
		if (dsCepStaffs.size()>0) {
			for (DsCepStaff dsCepStaff : dsCepStaffs) {
				// Update the actual number of attention paid to sales consultants 
				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());
				}
			}
		}
	} 	
}

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;
/**
 *  Used for carrying out Https Requested 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));
    }
}

Related articles: