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

作者:西凉的悲伤 时间:2022-07-03 21:23:25 

使用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;
/**
* 授权接口
* 参数格式:
*{
*"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());
}
}
}
}
}

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

标签:Java,httpclient,url
0
投稿

猜你喜欢

  • Java两个乒乓球队比赛名单问题(判断素数)

    2022-11-15 08:39:20
  • C++日期类计算器的模拟实现举例详解

    2023-05-22 08:27:16
  • Java多线程 两阶段终止模式Two-Phase Termination Patter

    2023-11-29 04:47:04
  • Android11文件管理权限申请详细介绍

    2023-08-28 17:41:47
  • Android实现录音声波图

    2022-08-05 20:55:49
  • java 微信随机红包算法代码实例

    2022-12-03 12:29:08
  • Android Studio打包.so库到apk中实例详解

    2022-06-25 19:19:25
  • android同时控制EditText输入字符个数和禁止特殊字符输入的方法

    2021-08-01 14:16:46
  • Android输入框实时模糊搜索效果的示例代码

    2022-09-17 02:12:10
  • Android12四大组件之Activity生命周期变化详解

    2022-05-04 15:47:57
  • 在C#中根据HardwareID获取驱动程序信息的实现代码

    2023-08-04 08:15:31
  • DoytoQuery中关于N+1查询问题解决方案详解

    2022-06-14 12:03:07
  • Android从服务器获取图片的实例方法

    2022-08-27 04:03:46
  • C#多线程的相关操作讲解

    2022-01-13 18:32:12
  • SpringBoot扫描不到Controller的解决方案

    2022-07-19 02:05:07
  • 逆波兰计算器(Java实现)

    2021-10-18 09:45:01
  • C#中实现AES算法加密解读

    2022-09-17 16:49:36
  • java 线程的生命周期详解

    2023-05-28 08:32:25
  • 详解Java类库的概念以及import的使用方法

    2022-04-18 06:56:54
  • Android编程之ICS式下拉菜单PopupWindow实现方法详解(附源码下载)

    2021-07-30 00:27:24
  • asp之家 软件编程 m.aspxhome.com