Java使用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));
    }
}

你可能感兴趣的:(HttpClient)