Java如何使用httpclient檢測(cè)url狀態(tài)及鏈接是否能打開(kāi)
使用httpclient檢測(cè)url狀態(tài)及鏈接是否能打開(kāi)
有時(shí)候我們需要檢測(cè)某個(gè)url返回的狀態(tài)碼是不是200或者頁(yè)面能不能正常打開(kāi)響應(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;
}
//更新所有在職銷售顧問(wèn)實(shí)際被關(guān)注數(shù),此接口涉及內(nèi)部代碼,不做詳解
@Override
@Transactional
public void updateFacoriteCountRealitys() {
//獲取所有在職員工列表
List<DsCepStaff> dsCepStaffs = dsCepStaffDAO.getAllOnPost();
if (dsCepStaffs.size()>0) {
for (DsCepStaff dsCepStaff : dsCepStaffs) {
//更新銷售顧問(wèn)實(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)文章
Spring Boot實(shí)現(xiàn)對(duì)文件進(jìn)行壓縮下載功能
在Web應(yīng)用中,文件下載功能是一個(gè)常見(jiàn)的需求,特別是當(dāng)你需要提供用戶下載各種類型的文件時(shí),本文將演示如何使用Spring Boot框架來(lái)實(shí)現(xiàn)一個(gè)簡(jiǎn)單而強(qiáng)大的文件下載功能,需要的朋友跟隨小編一起學(xué)習(xí)吧2023-09-09
MyBatis使用Zookeeper保存數(shù)據(jù)庫(kù)的配置可動(dòng)態(tài)刷新的實(shí)現(xiàn)代碼
這篇文章主要介紹了MyBatis使用Zookeeper保存數(shù)據(jù)庫(kù)的配置,可動(dòng)態(tài)刷新,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08
java servlet獲得客戶端相關(guān)信息的簡(jiǎn)單代碼
這篇文章主要介紹了java servlet獲得客戶端相關(guān)信息的簡(jiǎn)單代碼,有需要的朋友可以參考一下2013-12-12
教你如何在IDEA?中添加?Maven?項(xiàng)目的?Archetype(解決添加不起作用的問(wèn)題)
這篇文章主要介紹了如何在?IDEA?中添加?Maven?項(xiàng)目的?Archetype(解決添加不起作用的問(wèn)題),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
springboot項(xiàng)目打成war包部署到tomcat遇到的一些問(wèn)題
這篇文章主要介紹了springboot項(xiàng)目打成war包部署到tomcat遇到的一些問(wèn)題,需要的朋友可以參考下2017-06-06
SpringSecurity授權(quán)實(shí)現(xiàn)基本思路
本文介紹了SpringSecurity中使用FilterSecurityInterceptor進(jìn)行權(quán)限校驗(yàn)的基本方法,通過(guò)SecurityContextHolder獲取Authentication中的權(quán)限信息,感興趣的朋友跟隨小編一起看看吧2024-10-10
關(guān)于快速測(cè)試API接口的一個(gè)新技能
這篇文章主要給大家介紹了關(guān)于快速測(cè)試API接口的一個(gè)新技能,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-06-06
IDEA使用jformdesigner插件做管理系統(tǒng)MVC架構(gòu)的步驟和實(shí)現(xiàn)思路
在?IntelliJ?IDEA?中結(jié)合?JFormDesigner?插件,通過(guò)?Swing?框架實(shí)現(xiàn)一個(gè)管理系統(tǒng)的?MVC?架構(gòu)是一種經(jīng)典的開(kāi)發(fā)方式,以下是具體的步驟和實(shí)現(xiàn)思路,包含從項(xiàng)目創(chuàng)建到?MVC?架構(gòu)的核心代碼實(shí)現(xiàn),需要的朋友可以參考下2024-12-12

