qq_41629512 2022-03-08 18:29 采纳率: 100%
浏览 43
已结题

这个main方法怎么改写成类


package com.pospal.openplatform;

import com.alibaba.fastjson.JSON;
import com.pospal.openplatform.common.Constants;
import com.pospal.openplatform.product.Product;
import com.pospal.openplatform.product.ProductPageRequest;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.util.DigestUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;

/**
 * 该类用于测试分页查询商品
 */
public class Main {

    //分页查询全部商品信息
    private static final String QUERY_PRODUCT_PAGES_URL = "customerOpenapi/queryBytel";

    public static void main(String[] args) throws IOException {
        ProductPageRequest productPageRequest = new ProductPageRequest();
        productPageRequest.setAppId(Constants.APP_ID);

        boolean queryNextPage;
        List<Product> allProducts = new ArrayList<>();
            String json = JSON.toJSONString(productPageRequest);
            String httpResponseContent = sendPost(QUERY_PRODUCT_PAGES_URL, json);
            System.out.println("返回值:" + httpResponseContent);
        System.out.println(String.format("总共返回%d个商品", allProducts.size()));
    }

    private static String sendPost(String url, String json) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        //1:appKey,请求体 拼接 2:md5 加密 3:转为大写
        String dataSignature = DigestUtils.md5DigestAsHex((Constants.APP_KEY + json).getBytes()).toUpperCase();

        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(Constants.HOST + url)
                .method("POST", body)
                .addHeader("data-signature", dataSignature)
                .addHeader("User-Agent", "openApi")
                .addHeader("accept-encoding", "gzip,deflate")
                .addHeader("time-stamp", String.valueOf(System.currentTimeMillis()))
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        return dealGzip(response);
    }

    //返回内容有可能是gzip压缩过的。根据response header 中的Content-Encoding自行解压
    private static String dealGzip(Response response) throws IOException {
        String contenEncodingHeader = response.header("Content-Encoding");
        if ("gzip".equals(contenEncodingHeader)) {
            InputStream inputStream = response.body().byteStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPInputStream gunzip = new GZIPInputStream(inputStream);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toString("utf-8");
        }
        return response.body().string();
    }

}
  • 写回答

2条回答 默认 最新

  • CSDN专家-sinJack 2022-03-08 18:42
    关注

    写成什么类?业务类吗,然后在main方法中调用?

    
     
    package com.pospal.openplatform;
     
    import com.alibaba.fastjson.JSON;
    import com.pospal.openplatform.common.Constants;
    import com.pospal.openplatform.product.Product;
    import com.pospal.openplatform.product.ProductPageRequest;
    import okhttp3.MediaType;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.RequestBody;
    import okhttp3.Response;
    import org.springframework.util.DigestUtils;
     
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.zip.GZIPInputStream;
     
    /**
     * 该类用于测试分页查询商品
     */
    @Controller
    public class MainController {
     
        //分页查询全部商品信息
        private static final String QUERY_PRODUCT_PAGES_URL = "customerOpenapi/queryBytel";
        @RequestMapping("/getProduct")
        @ResponseBody
        public String getProduct() throws IOException {
            ProductPageRequest productPageRequest = new ProductPageRequest();
            productPageRequest.setAppId(Constants.APP_ID);
     
            boolean queryNextPage;
            List<Product> allProducts = new ArrayList<>();
                String json = JSON.toJSONString(productPageRequest);
                String httpResponseContent = sendPost(QUERY_PRODUCT_PAGES_URL, json);
                System.out.println("返回值:" + httpResponseContent);
            return String.format("总共返回%d个商品", allProducts.size());
        }
      
       public static String sendPost(String url, String json) throws IOException {
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            MediaType mediaType = MediaType.parse("application/json");
            //1:appKey,请求体 拼接 2:md5 加密 3:转为大写
            String dataSignature = DigestUtils.md5DigestAsHex((Constants.APP_KEY + json).getBytes()).toUpperCase();
     
            RequestBody body = RequestBody.create(mediaType, json);
            Request request = new Request.Builder()
                    .url(Constants.HOST + url)
                    .method("POST", body)
                    .addHeader("data-signature", dataSignature)
                    .addHeader("User-Agent", "openApi")
                    .addHeader("accept-encoding", "gzip,deflate")
                    .addHeader("time-stamp", String.valueOf(System.currentTimeMillis()))
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            return dealGzip(response);
        }
     
        //返回内容有可能是gzip压缩过的。根据response header 中的Content-Encoding自行解压
        private static String dealGzip(Response response) throws IOException {
            String contenEncodingHeader = response.header("Content-Encoding");
            if ("gzip".equals(contenEncodingHeader)) {
                InputStream inputStream = response.body().byteStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                GZIPInputStream gunzip = new GZIPInputStream(inputStream);
                byte[] buffer = new byte[256];
                int n;
                while ((n = gunzip.read(buffer)) >= 0) {
                    out.write(buffer, 0, n);
                }
                return out.toString("utf-8");
            }
            return response.body().string();
        }
     
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 3月11日
  • 已采纳回答 3月9日
  • 修改了问题 3月8日
  • 创建了问题 3月8日

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀