Java如何使用httpclient檢測url狀態(tài)及鏈接是否能打開
使用httpclient檢測url狀態(tài)及鏈接是否能打開
有時(shí)候我們需要檢測某個(gè)url返回的狀態(tài)碼是不是200或者頁面能不能正常打開響應(yīng)可使用如下代碼:
需要使用到的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) { // 創(chuàng)建http POST請(qǐng)求 HttpGet httpGet = new HttpGet(url); httpGet.setHeader("Content-Type", "application/json"); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(600)// 設(shè)置連接主機(jī)服務(wù)超時(shí)時(shí)間 .setConnectionRequestTimeout(1000)// 設(shè)置連接請(qǐng)求超時(shí)時(shí)間 .setSocketTimeout(1000)// 設(shè)置讀取數(shù)據(jù)連接超時(shí)時(shí)間 .build(); // 為httpPost實(shí)例設(shè)置配置 httpGet.setConfig(requestConfig); // 設(shè)置請(qǐng)求頭 CloseableHttpClient httpclient = null; CloseableHttpResponse response = null; int statusCode = 404; try { httpclient = HttpClients.createDefault();// 創(chuàng)建Httpclient對(duì)象 response = httpclient.execute(httpGet);// 執(zhí)行請(qǐng)求 statusCode = response.getStatusLine().getStatusCode(); }catch (SocketException e) { return "404"; } catch (IOException e) { System.out.println("報(bào)錯(cuò)"); return "404"; } return String.valueOf(statusCode); }
HTTPClient調(diào)用遠(yuǎn)程URL實(shí)例
案例描述
一次項(xiàng)目中后端服務(wù)需要從微信小程序獲取掃碼關(guān)注次數(shù),網(wǎng)上搜各種示例都不太好用(代碼冗余且效果不佳),于是自己花功夫做了一套。
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; /** * 授權(quán)接口 * 參數(shù)格式: *{ * "Client":"digital_xxx",//客戶端標(biāo)識(shí) * "Secret":"@-!xxx"http://客戶端接入秘鑰 *} */ @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,以便于下一個(gè)接口調(diào)用 return msgData.get("Token").toString(); } /** * 微信小程序關(guān)注次數(shù)接口,POST請(qǐng)求 */ @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; } //更新所有在職銷售顧問實(shí)際被關(guān)注數(shù),此接口涉及內(nèi)部代碼,不做詳解 @Override @Transactional public void updateFacoriteCountRealitys() { //獲取所有在職員工列表 List<DsCepStaff> dsCepStaffs = dsCepStaffDAO.getAllOnPost(); if (dsCepStaffs.size()>0) { for (DsCepStaff dsCepStaff : dsCepStaffs) { //更新銷售顧問實(shí)際被關(guān)注數(shù) 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; /** * 用于進(jìn)行Https請(qǐng)求的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)); } }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)現(xiàn)驗(yàn)證文件名有效性的方法詳解
在本文中,我們將討論使用?Java?驗(yàn)證一個(gè)給定的字符串是否具有操作系統(tǒng)的有效文件名的不同方法,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2022-09-09java實(shí)現(xiàn)文本文件刪除空行的示例分享
這篇文章主要介紹了java實(shí)現(xiàn)文本文件刪除空行的示例,需要的朋友可以參考下2014-04-04java實(shí)現(xiàn)動(dòng)態(tài)時(shí)鐘并設(shè)置鬧鐘功能
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)動(dòng)態(tài)時(shí)鐘并設(shè)置鬧鐘功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01SpringBoot實(shí)現(xiàn)quartz定時(shí)任務(wù)可視化管理功能
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)quartz定時(shí)任務(wù)可視化管理功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08Java中位運(yùn)算(移位、位與、或、異或、非) 的簡單實(shí)例
Java中位運(yùn)算(移位、位與、或、異或、非) 的簡單實(shí)例,需要的朋友可以參考一下2013-02-02java通過HttpServletRequest獲取post請(qǐng)求中的body內(nèi)容的方法
本篇文章主要介紹了java通過HttpServletRequest獲取post請(qǐng)求中的body內(nèi)容的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02