使用OKHttp代替原生http请求调用微信支付及Okhttp常用方法

前言:每次看到原生的http请求,不只是看起来难受,使用起来也难受,因为刚毕业时开发了半年的android,okhttp+rxjava使用也是得心应手(后端比安卓舒服的一点是,直接请求即可,不用考虑网络请求会阻塞UI线程这种东西),完全转后端后,偶尔也还是会用到http请求的,但是原生的确实难用,所以每次都是使用okhttp解决的,最近接触了一下微信支付,示例给的demo还是原生的,也是看的难受,所以下面简单的封装了一下基于okhttp微信支付的方法。

下面的示例是企业支付到用户的方法,其他的大同小异,代码如下:

/**
     * 微信企业支付到用户操作
     *
     * @param requestData  请求的数据
     * @param keystorePath 签名文件路径
     * @return
     */
    public static Map<String, String> wxTransfers(String url, Map<String, String> requestData, String mchid,  String keystorePath) throws Exception {
        if (requestData == null || requestData.isEmpty() || StringUtils.isEmpty(keystorePath)) {
            throw new Exception("requestData or keyStorePath can't be null or empty");
        }

        String requestParam = WXPayUtil.mapToXml(requestData);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream inputStream = new FileInputStream(new File(keystorePath));
        try {
            keyStore.load(inputStream, mchid.toCharArray());
        } finally {
            inputStream.close();
        }
        SSLContext sslContext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, mchid.toCharArray())
                .build();

        if (sslContext == null) {
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("message", "获取证书文件失败");

            return resultMap;
        }

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(sslContext.getSocketFactory())
                .addInterceptor(chain -> {
                    Request request = chain.request()
                            .newBuilder()
                            .addHeader("Content-Type", "text/plain; charset=utf-8")
                            .addHeader("content", "text/plain; charset=utf-8")
                            .build();
                    return chain.proceed(request);
                })
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
        RequestBody requestBody = RequestBody.create(requestParam, OkHttpDataType.PLAIN_TYPE);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return WXPayUtil.xmlToMap(response.body().string());
        } else {
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("message", response.message());

            return resultMap;
        }
    }

 其中requestData是请求的数据,只要按照微信API中的参数,塞进map传递进来即可,不需要去排序什么的了,顺序随意,方法里的WXPayUtil.mapToXml是那的微信提供的demo中的方法,自行下载demo就能找到的。

        上面的方法中,还有个OkHttpDataType为OkHttp中的MediaType,完整类型如下所示:

 /**
     * HTML格式
     *
     * @return
     */
    public static final MediaType HTML_TYPE = MediaType.parse("text/html;charset=utf-8");

    /**
     * 纯文本格式
     *
     * @return
     */
    public static final MediaType PLAIN_TYPE = MediaType.parse("text/plain;charset=utf-8");

    /**
     * XML格式
     *
     * @return
     */
    public static final MediaType XML_TYPE = MediaType.parse("text/xml;charset=utf-8");

    /**
     * gif图片格式
     *
     * @return
     */
    public static final MediaType GIF_TYPE = MediaType.parse("image/gif");

    /**
     * jpg图片格式
     *
     * @return
     */
    public static final MediaType JPG_TYPE = MediaType.parse("image/jpeg");

    /**
     * png图片格式
     *
     * @return
     */
    public static MediaType PNG_TYPE = MediaType.parse("image/png");

    /**
     * XHTML格式
     *
     * @return
     */
    public static final MediaType XHTML_TYPE = MediaType.parse("application/xhtml+xml;charset=utf-8");

    /**
     * XML数据格式
     *
     * @return
     */
    public static final MediaType XML_DATA_TYPE = MediaType.parse("application/xml;charset=utf-8");

    /**
     * Atom XML聚合格式
     *
     * @return
     */
    public static final MediaType ATOM_XML_TYPE = MediaType.parse("application/atom+xml;charset=utf-8");

    /**
     * JSON数据格式
     *
     * @return
     */
    public static final MediaType JSON_TYPE = MediaType.parse("application/json;charset=utf-8");

    /**
     * pdf格式
     *
     * @return
     */
    public static final MediaType PDF_TYPE = MediaType.parse("application/pdf");

    /**
     * Word文档格式
     *
     * @return
     */
    public static final MediaType WORD_TYPE = MediaType.parse("application/msword");

    /**
     * 二进制流数据(如常见的文件下载)
     *
     * @return
     */
    public static final MediaType STREAM_TYPE = MediaType.parse("application/octet-stream");

    /**
     * <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器
     *
     * @return
     */
    public static final MediaType ENC_TYPE = MediaType.parse("application/x-www-form-urlencoded");

    /**
     * 另外一种常见的媒体格式是上传文件之时使用的
     * 需要在表单中进行文件上传时,就需要使用该格式
     *
     * @return
     */
    public static final MediaType FORM_DATA_TYPE = MediaType.parse("multipart/form-data");

       下面是一些常用的基于OkHttp封装的简单请求,更多的使用方式,请查阅OkHttp官当文档,不过目前最新的OkHttp已经是基于kotlin开发了,看起来不错,个人表示很喜欢kotlin,也把kotlin用在项目上了,简单封装的代码如下:

 /**
     * get请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String doGet(String url) throws Exception {
        if (StringUtils.isEmpty(url)) {
            throw new Exception("url can't be null or empty");
        }
        if (!url.startsWith("http")) {
            throw new IllegalArgumentException("requst url illegal");
        }
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return response.message();
        }
    }

    /**
     * get请求并返回数据
     *
     * @param url               请求链接
     * @param connectionTimeOut 请求时间
     * @return
     */
    public static String doGet(String url, int connectionTimeOut) throws Exception {
        if (StringUtils.isEmpty(url)) {
            throw new Exception("url can't be null or empty");
        }
        if (!url.startsWith("http")) {
            throw new IllegalArgumentException("requst url illegal");
        }
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return response.message();
        }
    }

    /**
     * 带请求头的get请求
     *
     * @param url
     * @param headers
     * @return
     * @throws Exception
     */
    public static String doGet(String url, Map<String, String> headers) throws Exception {
        if (StringUtils.isEmpty(url)) {
            throw new Exception("url can't be null or empty");
        }
        if (!url.startsWith("http")) {
            throw new IllegalArgumentException("requst url illegal");
        }
        if (headers == null || headers.isEmpty()) {
            throw new Exception("header can't be null or empty");
        }

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(chain -> chain.proceed(chain.request().newBuilder().headers(Headers.of(headers)).build()))
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return response.message();
        }
    }

    /**
     * 带请求头的get请求
     *
     * @param url               请求链接
     * @param connectionTimeOut 请求超时限制(单位为秒)
     * @param headers           请求头
     * @return
     * @throws Exception
     */
    public static String doGet(String url, int connectionTimeOut, Map<String, String> headers) throws Exception {
        if (StringUtils.isEmpty(url)) {
            throw new Exception("url can't be null or empty");
        }
        if (!url.startsWith("http")) {
            throw new IllegalArgumentException("requst url illegal");
        }
        if (headers == null || headers.isEmpty()) {
            throw new Exception("header can't be null or empty");
        }

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(chain -> chain.proceed(chain.request().newBuilder().headers(Headers.of(headers)).build()))
                .connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return response.message();
        }
    }

    /**
     * post请求
     *
     * @param url
     * @param data
     * @return
     * @throws Exception
     */
    public static String doPost(String url, String data) throws Exception {
        if (StringUtils.isEmpty(url)) {
            throw new Exception("url can't be null or empty");
        }
        if (!url.startsWith("http")) {
            throw new IllegalArgumentException("requst url illegal");
        }

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .callTimeout(10, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(data, OkHttpDataType.JSON_TYPE))
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return response.message();
        }
    }

    /**
     * post请求
     *
     * @param url               请求链接
     * @param connectionTimeOut 请求超时限制(单位:秒)
     * @param data
     * @return
     * @throws Exception
     */
    public static String doPost(String url, int connectionTimeOut, String data) throws Exception {
        if (StringUtils.isEmpty(url)) {
            throw new Exception("url can't be null or empty");
        }
        if (!url.startsWith("http")) {
            throw new IllegalArgumentException("requst url illegal");
        }

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
                .callTimeout(connectionTimeOut, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(data, OkHttpDataType.JSON_TYPE))
                .build();
        Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return response.message();
        }
    }

    /**
     * post请求数据
     *
     * @param url
     * @param data
     * @param connectionTimeOut
     * @param headers
     * @return
     */
    public static String doPost(String url, String data, int connectionTimeOut, final Map<String, String> headers) throws Exception {
        if (StringUtils.isEmpty(url)) {
            throw new Exception("url can't be null or empty");
        }
        if (!url.startsWith("http")) {
            throw new IllegalArgumentException("requst url illegal");
        }
        if (headers == null || headers.isEmpty()) {
            throw new Exception("header can't be null or empty");
        }
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(chain -> chain.proceed(chain.request().newBuilder().headers(Headers.of(headers)).build()))
                .connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
                .build();
        RequestBody requestBody = RequestBody.create(data, OkHttpDataType.JSON_TYPE);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return null;
        }
    }

    /**
     * post请求数据
     *
     * @param url
     * @param data
     * @param connectionTimeOut
     * @param headers
     * @return
     */
    public static String doPost(String url, String data, int connectionTimeOut, MediaType type, final Map<String, String> headers) throws Exception {
        if (StringUtils.isEmpty(url)) {
            throw new Exception("url can't be null or empty");
        }
        if (!url.startsWith("http")) {
            throw new IllegalArgumentException("requst url illegal");
        }
        if (headers == null || headers.isEmpty()) {
            throw new Exception("header can't be null or empty");
        }
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(chain -> chain.proceed(chain.request().newBuilder().headers(Headers.of(headers)).build()))
                .connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
                .build();
        RequestBody requestBody = RequestBody.create(data, type);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return null;
        }
    }

    /**
     * post请求数据
     *
     * @param url
     * @param data
     * @param connectionTimeOut
     * @param headerMap
     * @return
     */
    public static String doPostWithAuthorization(String url, String data, final String credential, int connectionTimeOut, final Map<String, String> headerMap) throws IOException {
        if (url == null || data == null) {
            throw new NullPointerException("url or data can't be null");
        }
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .authenticator((route, response) -> response.request().newBuilder()
                        .header("Authorization", credential)
                        .build())
                .addInterceptor(chain -> {
                    Request request = null;
                    if (headerMap == null) {
                        request = chain.request()
                                .newBuilder()
                                .addHeader("Content-Type", "application/json;utf-8")
                                .build();
                    } else {
                        Headers headers = Headers.of(headerMap);
                        request = chain.request().newBuilder().headers(headers).build();
                    }

                    return chain.proceed(request);
                })
                .connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
                .build();
        RequestBody requestBody = RequestBody.create(data, OkHttpDataType.JSON_TYPE);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return null;
        }
    }

    /**
     * post提交表单数据
     *
     * @param url
     * @param data
     * @param connectionTimeOut
     * @param headerMap
     * @return
     */
    public static String doPostWithForm(String url, HashMap<String, Object> data, int connectionTimeOut, final Map<String, String> headerMap) throws IOException {
        if (url == null || data == null) {
            throw new NullPointerException("url or data can't be null");
        }
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(chain -> {
                    Request request = null;
                    if (headerMap == null) {
                        request = chain.request()
                                .newBuilder()
                                .addHeader("Content-Type", "application/json;utf-8")
                                .build();
                    } else {
                        Headers headers = Headers.of(headerMap);
                        request = chain.request().newBuilder().headers(headers).build();
                    }

                    return chain.proceed(request);
                })
                .connectTimeout(connectionTimeOut, TimeUnit.SECONDS)
                .build();
        // 构建请求数据表单
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : data.keySet()) {
            builder.add(key, String.valueOf(data.get(key)));
        }

        Request request = new Request.Builder()
                .post(builder.build())
                .url(url)
                .build();
        Response response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            return null;
        }
    }

好了,要说的就到这把,希望能帮到需要帮的人。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个Java开发的框架,提供了丰富的功能和便捷的开发方式。而OkHttp是一个开源的HTTP客户端,支持WebSocket协议。在Spring Boot中,我们可以使用OkHttp3来模拟客户端请求WebSocket。 首先,我们需要在pom.xml文件中添加OkHttp3的依赖: ```xml <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.14.9</version> </dependency> ``` 接下来,在Spring Boot的配置文件中,我们需要配置WebSocket的相关信息,包括WebSocket的地址和消息处理器等。以下是一个示例配置: ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myWebSocketHandler(), "/websocket").setAllowedOrigins("*"); } @Bean public WebSocketHandler myWebSocketHandler() { return new MyWebSocketHandler(); } } ``` 在MyWebSocketHandler类中,我们可以编写WebSocket的消息处理逻辑: ```java public class MyWebSocketHandler extends TextWebSocketHandler { @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); // 处理消息 session.sendMessage(new TextMessage("Hello, " + payload)); } } ``` 最后,我们可以使用OkHttp3来模拟客户端请求WebSocket。以下是一个示例代码: ```java OkHttpClient client = new OkHttpClient.Builder().build(); Request request = new Request.Builder() .url("ws://localhost:8080/websocket") .build(); WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() { @Override public void onOpen(WebSocket webSocket, Response response) { // 连接打开时的逻辑 webSocket.send("Hello, Server!"); } @Override public void onMessage(WebSocket webSocket, String text) { // 接收到消息时的逻辑 System.out.println("Received message: " + text); webSocket.close(1000, "Goodbye, Server!"); } @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) { // 连接失败时的逻辑 t.printStackTrace(); } }); ``` 以上就是使用OkHttp3模拟客户端请求WebSocket的基本步骤。通过配置WebSocket和编写消息处理逻辑,我们可以实现WebSocket的双向通信。同时,使用OkHttp3可以方便地发送和接收WebSocket消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值