使用HttpPost与HttpGet调用第三方接口

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dhcc.tms.webService.stockOutInfo.dto.TokenRes;
import com.dhcc.tms.webService.stockOutInfo.dto.GetStockOutlistReqConfig;
import com.dhcc.tms.webService.stockOutInfo.dto.GetStockOutlistReqParams;
import com.dhcc.tms.webService.stockOutInfo.dto.StockOut;
import com.dhcc.tms.webService.stockOutInfo.dto.TokenReqConfig2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
public class GetStockOutlist {

    private TokenReqConfig2 tokenReq;
    private GetStockOutlistReqConfig getStockOutlistReq;


    /**
     * 获取token
     */
    public TokenRes getToken() throws Exception {
        Map<String, Object> params = new HashMap<String, Object>() {
            {
                put("grant_type", tokenReq.getGrantType());
                put("scope", tokenReq.getScope());
                put("username", tokenReq.getUsername());
                put("password", tokenReq.getPassword());
            }
        };

        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(tokenReq.getUrl());
        // 设置请求头
        httpPost.addHeader("Content-Type", tokenReq.getContentType());
        httpPost.addHeader("Authorization", tokenReq.getAuthorization());
        httpPost.addHeader("Tenant-Id", tokenReq.getTenantId());
        // 封装post请求参数
        if (null != params && params.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通过map集成entrySet方法获取entity
            Set<Map.Entry<String, Object>> entrySet = params.entrySet();
            // 循环遍历,获取迭代器
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }
            // 为httpPost设置封装好的请求参数
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        }

        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(35000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                .setSocketTimeout(60000)// 设置读取数据连接超时时间
                .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);

        String result = "";
        // 创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                httpResponse.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        }

        //转换成为JSONObject对象
        org.springframework.boot.configurationprocessor.json.JSONObject jsonObj = new org.springframework.boot.configurationprocessor.json.JSONObject(result);
        if (StringUtils.isBlank(jsonObj.getString("token_type"))) {
            throw new Exception("token获取失败");
        }
        TokenRes res = new TokenRes();
        res.setToken_type(jsonObj.getString("token_type"));
        res.setAccess_token(jsonObj.getString("access_token"));
        res.setUser_name(jsonObj.getString("user_name"));
        res.setReal_name(jsonObj.getString("real_name"));
        return res;
    }


    /**
     * 助销物料销售出库单
     */
    public List<StockOut> getStockOutlist(GetStockOutlistReqParams reqParams, TokenRes tokenRes) throws Exception {
        if (StringUtils.isBlank(reqParams.getFactoryCode())
                || StringUtils.isBlank(reqParams.getInventoryCode())
                || StringUtils.isBlank(reqParams.getCreateTimeStart())
                || StringUtils.isBlank(reqParams.getCreateTimeEnd())) {
            throw new RuntimeException("缺失必填参数,请检查:工厂编码、库存地点编码、开始时间、结束时间!");
        }

        /*
         * 由于GET请求的参数都是拼装在URL地址后方,所以我们要构建一个URL,带参数
         */
        URIBuilder uriBuilder = new URIBuilder(getStockOutlistReq.getUrl());
        uriBuilder.addParameter("factoryCode", reqParams.getFactoryCode());
        uriBuilder.addParameter("inventoryCode", reqParams.getInventoryCode());
        uriBuilder.addParameter("createTimeStart", reqParams.getCreateTimeStart());
        uriBuilder.addParameter("createTimeEnd", reqParams.getCreateTimeEnd());
        // 根据带参数的URI对象构建GET请求对象
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        // 设置请求头
        httpGet.addHeader("Authorization", getStockOutlistReq.getAuthorization());
        httpGet.addHeader("Blade-Auth", tokenRes.getToken_type() + " " + tokenRes.getAccess_token());

        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(35000)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
                .setSocketTimeout(60000)// 设置读取数据连接超时时间
                .build();
        // 设置配置
        httpGet.setConfig(requestConfig);

        String result = "";
        // 创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        try {
            // 执行请求
            httpResponse = httpClient.execute(httpGet);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                httpResponse.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        }
        //转换成为JSONObject对象
        JSONObject json = JSON.parseObject(result);
        if (json.getIntValue("code") != 200) {
            throw new RuntimeException("外向交货单获取失败--->" + json.getString("msg"));
        }
        JSONArray jsonArray = json.getJSONArray("data");
        List<StockOut> resData = JSONObject.parseArray(jsonArray.toJSONString(), StockOut.class);
        return resData;
    }


    /**
     * 测试发送请求
     */
    public static void main(String[] args) throws Exception {
        GetStockOutlist demo = new GetStockOutlist();

        demo.tokenReq = new TokenReqConfig2(
                "POST",
                "http://xxx.com/blade-auth/oauth/token",
                "application/x-www-form-urlencoded",
                "Basic c2FiZXI6c2FiZXJfc2VjcmV0",
                "000000",
                "password",
                "all",
                "20139403",
                "e10adc3949ba59abbe56e057f20f883e"
        );
        TokenRes tokenRes = demo.getToken();
        log.info("=====getToken 结束=====");

        demo.getStockOutlistReq = new GetStockOutlistReqConfig(
                "GET",
                "http://xxx.com/blade-warehouse/stockOutInfo/getStockOutlist",
                "multipart/form-data",
                "Basic c2FiZXI6c2FiZXJfc2VjcmV0"
        );
        List<StockOut> stockOutlist = demo.getStockOutlist(
                new GetStockOutlistReqParams(
                        "S110", "6000",
                        "2021-04-01", "2021-06-01"
                ),
                tokenRes
        );
        log.info("=====getStockOutlist 结束=====");
    }
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TokenReqConfig2 {
    private String method;

    private String url;
    private String contentType;
    private String authorization;
    private String tenantId;

    private String grantType;
    private String scope;
    private String username;
    private String password;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TokenRes{
    private String token_type;
    private String access_token;
    private String user_name;
    private String real_name;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GetStockOutlistReqConfig {
    private String method;

    private String url;
    private String contentType;
    private String authorization;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GetStockOutlistReqParams {
    /**
     * 工厂编码
     */
    private String factoryCode;
    /**
     * 库存地点编码
     */
    private String inventoryCode;
    /**
     * 开始时间
     */
    private String createTimeStart;
    /**
     * 结束时间
     */
    private String createTimeEnd;
}```

```java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class StockOut {
    /**
     * 工厂编码
     */
    @ColumnWidth(15)
    @ExcelProperty("工厂编码")
    private String factoryCode;
    /**
     * 工厂名称
     */
    @ColumnWidth(15)
    @ExcelProperty("工厂名称")
    private String factoryName;
    /**
     * 库存地点编码
     */
    @ColumnWidth(20)
    @ExcelProperty("库存地点编码")
    private String inventoryCode;
    /**
     * 库存地点名称
     */
    @ColumnWidth(20)
    @ExcelProperty("库存地点名称")
    private String inventoryName;
    /**
     * 销售订单号
     */
    @ColumnWidth(20)
    @ExcelProperty("销售订单号")
    private String stockOrderNo;
    /**
     * 销售出库单号
     */
    @ColumnWidth(20)
    @ExcelProperty("销售出库单号")
    private String stockOutNo;
    /**
     * 销售组编码
     */
    @ColumnWidth(20)
    @ExcelProperty("销售组编码")
    private String salesGroupCode;
    /**
     * 销售组名称
     */
    @ColumnWidth(20)
    @ExcelProperty("销售组名称")
    private String salesGroupName;
    /**
     * 客户编码
     */
    @ColumnWidth(20)
    @ExcelProperty("客户编码")
    private String customerCode;
    /**
     * 客户名称
     */
    @ColumnWidth(40)
    @ExcelProperty("客户名称")
    private String customerName;
    /**
     * 出库单详情
     */
    @ExcelIgnore
    private List<StockOutDetail> detailVOList;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class StockOutDetail {
    /**
     * 物料编码
     */
    private String materialCode;
    /**
     * 物料名称
     */
    private String materialName;
    /**
     * 订单数量
     */
    private BigDecimal quantity;
    /**
     * 出库数量
     */
    private BigDecimal stockNum;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值