http调用微信接口

http调用微信接口

项目需求:调用微信消息和图片审核接口来判断我们微信小程序传过去的内容是否合法

基本思路:文本消息以Json格式穿过去,主要是传文本,这个比较简单

     图片微信接口要求以FormData格式传过去,项目中图片以URL形式传过来,所以用URL类获取图片的流,将流保存在byte数组中,再调用http接口的executeMethod(method)方法。

 

 

主要jar包

hamcrest-core-1.1.jar

fastjson-1.2.47.jar

commons-codec-1.10.jar

commons-logging-1.1.1.jar

commons-httpclient-3.1.jar

@Service(value = "weiXinCheckService")
public class WeiXinCheckServiceImpl implements WeiXinCheckService{
    
    private   String MSGURL = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=";
    private   String IMGURL = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=";
    
    @Resource
    MediaConfigService mediaConfigService;
    /**
     * 微信消息审核
     */
    @Override
    public WeiXinMsgCheckResponse checkWeiXinMsg(WeiXinMsgCheckRequest request) {
        
        WeiXinMsgCheckResponse response = new WeiXinMsgCheckResponse();
        PostMethod method = null;
        try {
            String content = request.getContent();
            DossMediaGetByMediaIdRequest dmrequest = new DossMediaGetByMediaIdRequest();
            dmrequest.setMediaSvrId(request.getMediaSvrId());
            dmrequest.setTenantNumId(request.getTenantNumId());
            dmrequest.setDataSign(request.getDataSign());
            //根据媒体编号获取token接口
            DossMediaGetResponse dossMediaGetResponse = mediaConfigService.dossMediaGetByMediaId(dmrequest);
            if(dossMediaGetResponse.getCode()!=0) {
                throw new BusinessException(Constant.SUB_SYSTEM, ExceptionType.BE40179,"根据媒体编号获取token失败,"+dossMediaGetResponse.getMessage());
            }
            String accessToken = dossMediaGetResponse.getAccessToken();
            
//            accessToken = "14_eYUDdgJSK42kQ4V43FIDGZnWMql_zO4Q683ihEq8_pQbuvANIpK4QGcm6qol1Agpt9RUNrSI0I37l8PrD2QDzwKSJmPuhQPyYiq2GRAfBQY3XIbKWjUQx66SRcx31N2E8H2SuNwLghSrmpbkTVEbAJAPRA";
            
            MSGURL = MSGURL + accessToken;
            HttpClient httpClient = new HttpClient();
            method = new PostMethod(MSGURL);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("content", content);  
            RequestEntity requestEntity = new StringRequestEntity(jsonObject.toJSONString(), "application/json", "UTF-8");
            method.setRequestEntity(requestEntity);
            int returnCode = httpClient.executeMethod(method);
            if (returnCode != 200) {
                throw new BusinessException(Constant.SUB_SYSTEM, ExceptionType.BE40179,"微信接口返回错误码:"+returnCode);
            }
            String wxResult = method.getResponseBodyAsString();
            JSONObject json = JSONObject.parseObject(wxResult);
            String errcode = json.getString("errcode");
            if(!errcode.equals("0")) {
                throw new BusinessException(Constant.SUB_SYSTEM, ExceptionType.BE40179,"微信接口调用失败,"+wxResult);
            }
        } catch (Exception e) {
            ExceptionUtil.processException(e, response);
        } finally {
            if(method!=null) {
                method.releaseConnection();
            }
        }
        return response;
    }

    @Override
    public WeiXinImgCheckResponse checkWeiXinImg(WeiXinImgCheckRequest request)  {
        
        WeiXinImgCheckResponse response = new WeiXinImgCheckResponse();
        InputStream is = null;
        PostMethod method = null;
        ByteArrayOutputStream baos = null;
        DossMediaGetByMediaIdRequest dmrequest = new DossMediaGetByMediaIdRequest();
        dmrequest.setMediaSvrId(request.getMediaSvrId());
        dmrequest.setTenantNumId(request.getTenantNumId());
        dmrequest.setDataSign(request.getDataSign());
        //根据媒体编号获取token接口
        DossMediaGetResponse dossMediaGetResponse = mediaConfigService.dossMediaGetByMediaId(dmrequest);
        if(dossMediaGetResponse.getCode()!=0) {
            throw new BusinessException(Constant.SUB_SYSTEM, ExceptionType.BE40179,"根据媒体编号获取token失败,"+dossMediaGetResponse.getMessage());
        }
        String accessToken = dossMediaGetResponse.getAccessToken();
        
//        accessToken="14_eYUDdgJSK42kQ4V43FIDGZnWMql_zO4Q683ihEq8_pQbuvANIpK4QGcm6qol1Agpt9RUNrSI0I37l8PrD2QDzwKSJmPuhQPyYiq2GRAfBQY3XIbKWjUQx66SRcx31N2E8H2SuNwLghSrmpbkTVEbAJAPRA";
        
        String wxUrl = "https://api.weixin.qq.com/wxa/img_sec_check?access_token="+accessToken;
        try {
            URL url = new URL(request.getUrl());
            is = url.openStream();
            HttpClient httpClient = new HttpClient();
            method = new PostMethod(wxUrl);
            baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = is.read(b)) != -1) {
                baos.write(b, 0, len);
            }
            byte[] buffer =  baos.toByteArray();
            Part[] parts = { new FilePart("media", new ByteArrayPartSource("media", buffer)) };
            RequestEntity requestEntity = new MultipartRequestEntity(parts, method.getParams());
            method.setRequestEntity(requestEntity);
            int returnCode = httpClient.executeMethod(method);
            if (returnCode != 200) {
                throw new BusinessException(Constant.SUB_SYSTEM, ExceptionType.BE40179,"微信接口返回错误码:"+returnCode);
            }
            String wxResult = method.getResponseBodyAsString();
            JSONObject json = JSONObject.parseObject(wxResult);
            String errcode = json.getString("errcode");
            if(!errcode.equals("0")) {
                throw new BusinessException(Constant.SUB_SYSTEM, ExceptionType.BE40179,"微信接口调用失败,"+wxResult);
            }
        } catch (Exception e) {
            ExceptionUtil.processException(e, response);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }  
        return response;
    }
}

 




posted on 2018-10-23 16:25  最后一个java菜鸟  阅读(2876)  评论(0编辑  收藏  举报

导航