广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Java如何使用httpclient检测url状态及链接是否能打开
  • 641
分享到

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

2024-04-02 19:04:59 641人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录使用Httpclient检测url状态及链接是否能打开需要使用到的MavenHTTPClient调用远程URL实例案例描述使用httpclient检测url状态及链接是否能打开

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

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

需要使用到的maven


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

代码:


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

案例描述

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


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;
	
	@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();
	}
	
	@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());
				}
			}
		}
	} 	
}

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;

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));
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: Java如何使用httpclient检测url状态及链接是否能打开

本文链接: https://www.lsjlt.com/news/135991.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作