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

目录
  • 使用httpclient检测url状态及链接是否能打开
    • 需要使用到的maven
  • 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;
	/**
	 * 授权接口
	 * 参数格式:
	 *{
	 *	"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));
    }
}

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

(0)

相关推荐

  • httpclient重定向之后获取网址信息示例

    复制代码 代码如下: import org.apache.http.HttpEntity;import org.apache.http.HttpHost;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpUriReque

  • JAVA利用HttpClient进行POST请求(HTTPS)实例

    最近,需要对客户的接口做一个包装,然后供自己公司别的系统调用,客户接口是用HTTP URL实现的,我想用HttpClient包进行请求,同时由于请求的URL是HTTPS的,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程. 1.写一个SSLClient类,继承至HttpClient package com.pcmall.service.sale.miaomore.impl; import java.security.cert.CertificateExcept

  • java发送HttpClient请求及接收请求结果过程的简单实例

    一. 1.写一个HttpRequestUtils工具类,包括post请求和get请求 package com.brainlong.framework.util.httpclient; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpStatus; import org.apache.http.HttpResponse; import org.apache.http.client.methods.Htt

  • 基于HttpClient在HTTP协议接口测试中的使用(详解)

    HTTP协议的接口测试中,使用到最多的就是GET请求与POST请求,其中POST请求有FORM参数提交请求与RAW请求,下面我将结合HttpClient来实现一下这三种形式: 一.GET请求: GET请求时,参数一般是写在链接上的,代码如下: public void get(String url){ CloseableHttpClient httpClient = null; HttpGet httpGet = null; try { httpClient = HttpClients.creat

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

    目录 使用httpclient检测url状态及链接是否能打开 需要使用到的maven HTTPClient调用远程URL实例 案例描述 使用httpclient检测url状态及链接是否能打开 有时候我们需要检测某个url返回的状态码是不是200或者页面能不能正常打开响应可使用如下代码: 需要使用到的maven <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpc

  • 利用Python检测URL状态

    需求:Python检测URL状态,并追加保存200的URL 代码一: #! /usr/bin/env python #coding=utf-8 import sys import requests def getHttpStatusCode(url): try: request = requests.get(url) httpStatusCode = request.status_code return httpStatusCode except requests.exceptions.HTTP

  • Java如何使用HTTPclient访问url获得数据

    目录 使用HTTPclient访问url获得数据 1.使用get方法取得数据 2.使用POST方法取得数据 使用httpclient后台调用url方式 使用HTTPclient访问url获得数据 最近项目上有个小功能需要调用第三方的http接口取数据,用到了HTTPclient,算是做个笔记吧! 1.使用get方法取得数据 /** * 根据URL试用get方法取得返回的数据 * @param url * URL地址,参数直接挂在URL后面即可 * @return */ public static

  • java发送http请求并获取状态码的简单实例

    目前做项目中有一个需求是这样的,需要通过java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page/qizha/pros_add.jsp"); try { HttpURLConnection uConnection = (HttpURLConnection) u.openConnection(); try { uConnection.connect(); Sy

  • 学习Java多线程之线程定义、状态和属性

    一 .线程和进程 1. 什么是线程和进程的区别: 线程是指程序在执行过程中,能够执行程序代码的一个执行单元.在java语言中,线程有四种状态:运行 .就绪.挂起和结束. 进程是指一段正在执行的程序.而线程有事也被成为轻量级的进程,他得程序执行的最小单元,一个进程可以拥有多个线程,各个线程之间共享程序的内功空间(代码段.数据段和堆空间)及一些进程级的资源(例如打开的文件),但是各个线程都拥有自己的棧空间. 2. 为何要使用多进程 在操作系统级别上来看主要有以下几个方面: - 使用多线程可以减少程序

  • Java Swing实现JTable检测单元格数据变更事件的方法示例

    本文实例讲述了Java Swing实现JTable检测单元格数据变更事件的方法.分享给大家供大家参考,具体如下: 在JTable的初级教程中往往会提到,使用TableModel的 addTableModelListener方法可以监听单元格数据的变更,在其事件处理函,数tableChanged中,可以通过e.getColumn(),e.getFirstRow(),e.getLastRow(),e.getType()来获取变更发生的位置和变更的类型(插入.更新或删除).然而该方法存在2个致命的问题

  • django 装饰器 检测登录状态操作

    1.检测登录状态 base.py def checkLogin(func): """ 查看session值用来判断用户是否已经登录 :param func: :return: """ def warpper(request,*args,**kwargs): if request.session.get('username', False): return func(request, *args, **kwargs) else: return Ht

  • HttpClient 请求 URL字符集转码问题

    问题是这样的,我用eclipse发送httpclient请求如下没有问题,但是在idea中就返回400,为毛呢???excuse me? package com.vol.timingTasks; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePassw

  • Java爬虫Jsoup+httpclient获取动态生成的数据

    Java爬虫Jsoup+httpclient获取动态生成的数据 前面我们详细讲了一下Jsoup发现这玩意其实也就那样,只要是可以访问到的静态资源页面都可以直接用他来获取你所需要的数据,详情情跳转-Jsoup爬虫详解,但是很多时候网站为了防止数据被恶意爬取做了很多遮掩,比如说加密啊动态加载啊,这无形中给我们写的爬虫程序造成了很大的困扰,那么我们如何来突破这个梗获取我们急需的数据呢, 下面我们来详细讲解一下如何获取 String startPage="https://item.jd.com/1147

  • iOS 检测网络状态的两种方法

    一般有两种方式,都是第三方的框架,轮子嘛,能用就先用着,后面再优化. 一:Reachability 1.首先在AppDelegate.h添加头文件"Reachability.h",导入框架SystemConfiguration.frame. 2. 在AppDelegate.m中这样实现: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launc

随机推荐