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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程