HttpClient 调用示例

import com.alibaba.fastjson.JSON;
import com.software.boot.common.entity.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@RefreshScope
public class TodoServiceImpl implements TodoService {


    @Autowired
    RestTemplate restTemplate;

    @Value("${micro.service.RY.service}")
    private String ryUrl;
    @Value("${micro.service.RY.ryBriefs}")
    private String ryBriefs;

    @Override
    public Response<?> list(TodoRequest request) {
        request.setScheduleDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.set("employeeId", request.getEmployeeId());
        log.info(">>>> Method:todoList>>Begin request:{}", request);
        HttpEntity<String> entity = new HttpEntity<String>("", headers);
        ResponseEntity<YqApiResult> responseEntity = restTemplate.exchange(ryUrl + "/integrate/yq/getSchedule?shopId=" + request.getShopId() + "&userCode=" + request.getEmployeeId(), HttpMethod.GET, entity, YqApiResult.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        int code = statusCode.value();
        log.info(">>> " + ryUrl + "/integrate/yq/getSchedule,result http status: {}", code);
        YqApiResult body = responseEntity.getBody();
        log.info(">>> /integrate/yq/getSchedule,response body: {}", body);
        if (body == null) {
            return Response.error(BusinessError.CALL_FAILED);
        }
        List<TodoResponse> data = body.getData();
        return Response.success(getQuantity(request, data));
    }


    /**
     * 查询待办数量
     *
     * @param quest
     * @param data
     * @return
     */
    private List<TodoResponse> getQuantity(TodoRequest quest, List<TodoResponse> data) {
        try {
            if (data == null) {
                return data;
            }
            List<ScheduleCode> codeList = new ArrayList<>();
            data.forEach(item -> {
                ScheduleCode codeItem = new ScheduleCode();
                codeItem.setScheduleCode(item.getScheduleCode());
                codeList.add(codeItem);
            });

            TodoIconRequest request = new TodoIconRequest();
            request.setData(codeList);
            request.setShopId(quest.getShopId());
            request.setUserCode(quest.getEmployeeId());
            request.setScheduleDate(quest.getScheduleDate());


            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            requestHeaders.set("employeeId", quest.getEmployeeId());
            requestHeaders.set("token", quest.getToken());
            requestHeaders.set("innerToken", ryBriefs);
            log.info(">>> Req quantity {},request header {}", JSON.toJSON(request), requestHeaders);
            HttpEntity<TodoIconRequest> requestEntity = new HttpEntity<>(request, requestHeaders);
            ResponseEntity<YqApiQuantityResult> quantityResp = null;
            quantityResp = restTemplate.postForEntity(ryUrl + "/schedule/yq/getScheduleQuantity", requestEntity, YqApiQuantityResult.class);
            log.info(">>> Quantity response,{}", quantityResp);
//            YqApiQuantityResult body = JSON.parseObject(JSON.toJSONString(quantityResponse), new TypeReference<YqApiQuantityResult>() {
//            });
            YqApiQuantityResult body = quantityResp.getBody();
            if (body == null) {
                return data;
            }
            List<TodoIconResponse> numData = body.getData();
            if (numData != null) {
                Map<String, Integer> buMap = numData.stream().collect(Collectors.toMap(TodoIconResponse::getScheduleCode, TodoIconResponse::getQuantity, (key1, key2) -> key1));
                //设置角标
                for (int i = 0; i < data.size(); i++) {
                    TodoResponse item = data.get(i);
                    Integer num = buMap.getOrDefault(item.getScheduleCode(), 0);
                    item.setQuantity(num == null ? 0 : num);
                    data.set(i, item);
                }
            }
            return data;
        } catch (Exception e) {
            log.info(">>> Call Failed {},use default 0", e.getMessage());
        }
        return data;
    }
}

  

上一篇:HttpClient学习笔记


下一篇:Feign HttpClient连接池