请求微信api(支持代理)

本文介绍了一种基于Java的HTTPS请求实现方式,该方法通过自定义HTTPSRequest类支持了代理功能,并详细展示了如何加载证书、配置连接参数及发送POST请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

微信给的demo中HttpsRequest笔者使用的时候不好使,索性只能以此为基础进行改造。
改造后的HttpsRequest如下:支持代理

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
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.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.tencent.service.IServiceRequest;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;

/**
 * 
 */

public class HttpsRequests implements IServiceRequest
{

    // 连接超时时间,默认10秒
    private int socketTimeout = 10000;

    // 传输超时时间,默认30秒
    private int connectTimeout = 30000;

    // HTTP请求器
    private DefaultHttpClient httpClient;

    public HttpsRequests() throws Exception
    {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // 根据规则查找商户对应证书
        FileInputStream instream = new FileInputStream(new File(Configure.getCertLocalPath()));// 加载本地的证书进行https加密传输
        try
        {
            // 证书密码默认为mchId
            keyStore.load(instream, Configure.getCertPassword().toCharArray());// 设置证书密码
        }
        catch (Exception e)
        {
            throw new RuntimeException("init throw Exception", e);
        }
        finally
        {
            try
            {
                instream.close();
            }
            catch (IOException e)
            {
            }
        }

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        // 证书密码默认为mchId
        SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore, Configure.getCertPassword());
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", socketFactory, 443);
        registry.register(sch);

        // 根据默认超时限制初始化requestConfig
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
        httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);

        //      //TODO 设置代理,生产环境需要去掉
        //      HttpHost proxy = new HttpHost("代理地址", 8080);
        //      CredentialsProvider credsProvider = new BasicCredentialsProvider();
        //      //TODO user\pwd改为代理用户密码
        //      UsernamePasswordCredentials creds = new UsernamePasswordCredentials("用户名", "密码");
        //      credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
        //      httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        //      httpClient.setCredentialsProvider(credsProvider);
    }

    /**
     * 通过Https往API post xml数据
     *
     * @param url
     *            API地址
     * @param xmlObj
     *            要提交的XML数据对象
     * @return API回包的实际数据
     * @throws IOException
     * @throws KeyStoreException
     * @throws UnrecoverableKeyException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */

    public String sendPost(String url, Object xmlObj, int flag)
    {
        String result = null;
        HttpPost httpPost = new HttpPost(url);

        // 将要提交给API的数据对象转换成XML格式数据Post给API
        String postDataXML = xmlObj.toString();
        if (flag == 0)
        {
            XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
            //将要提交给API的数据对象转换成XML格式数据Post给API
            postDataXML = xStreamForRequestPostData.toXML(xmlObj);
        }
        try
        {
            // 得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
            StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");
            httpPost.addHeader("Content-Type", "text/xml");
            httpPost.setEntity(postEntity);

            HttpResponse response = ((HttpClient) httpClient).execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
            {
                Header locationHeader = response.getFirstHeader("location");
                String location = null;
                if (locationHeader != null)
                {
                    location = locationHeader.getValue();
                    int index = location.indexOf("#");
                    String new_s = location.substring(0, index) + location.substring(index + 16);
                    return sendPost(new_s, xmlObj, flag);// 用跳转后的页面重新请求。
                }
            }

            HttpEntity entity = response.getEntity();

            result = EntityUtils.toString(entity, "UTF-8");

        }
        catch (Exception e)
        {
            throw new RuntimeException("http get throw Exception", e);

        }
        finally
        {
            httpPost.abort();
        }

        return result;
    }

    public static void main(String[] args) throws Exception
    {
        HttpsRequests hr = new HttpsRequests();
        String r = hr.sendPost("", "");
        System.out.println(r);
    }
}
public interface IServiceRequest
{

    //Service依赖的底层https请求器必须实现这么一个接口
    public String sendPost(String api_url, Object xmlObj, int flag) throws UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, IOException;

### 使用Python调用微信API的教程 #### 获取Access Token 为了能够成功调用微信API,开发者需要先获取`Access Token`。这可以通过向微信公众平台或企业微信申请并获得相应的AppID和AppSecret来完成。一旦有了这些凭证信息,就可以通过HTTP GET请求访问特定URL以换取access_token[^1]。 ```python import requests def get_access_token(appid, appsecret): url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}" response = requests.get(url).json() return response['access_token'] ``` #### 发送文本消息给用户 当获得了有效的`Access Token`之后,便可以利用它来进行各种操作,比如发送一条简单的文本消息至指定用户的OpenID列表中。下面是一个基于企业微信API的例子,展示了怎样构建这样的POST请求[^2]: ```python def send_text_message(access_token, user_ids, content): url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}' payload = { "touser": "|".join(user_ids), # 多个接收者之间用竖线分隔 "msgtype": "text", "agentid": YOUR_AGENT_ID, "text": {"content": content}, "safe": 0 } headers = {'Content-Type': 'application/json'} response = requests.post(url=url, json=payload, headers=headers).json() return response ``` 请注意,在实际应用时需替换`YOUR_AGENT_ID`为你自己的应用程序代理ID。 #### 集成OCR服务 对于想要在其项目里加入光学字符识别(OCR)能力的应用来说,还可以考虑使用微信提供的本地OCR SDK。这里给出了一段来自开源项目的样例代码片段,说明了如何在Python环境中加载图像并通过该SDK提取其中的文字数据[^3]: ```python from weixin_ocr_sdk import OCRClient def recognize_image_text(image_path): client = OCRClient('your_api_key', 'your_secret_key') result = client.recognize(image_path) text = '\n'.join([line['words'] for line in result]) return text ``` 上述函数接受一张图片路径作为输入参数,并返回由多行组成的字符串形式的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值