package com.ca.test.cainterface.common.util.http;

import com.ca.test.cainterface.common.util.data.Data;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
//import org.codehaus.jackson.map.ObjectMapper;
//import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Getter
@Setter
public class HttpClient {

    @Autowired
    RestTemplate restTemplate;
    private String sid = null;
    private String token;

    public HttpClient() {
        Data data = new Data();
        this.token = data.getRandomToken();
    }


    public boolean isCode200(ResponseEntity<String> responseEntity) {
        Integer code = responseEntity.getStatusCode().value();
        if (200 != code) {
            return true;
        }
        return false;
    }

    public String getUrl(String host, String path, String... urlParam) {
        return host + String.format(path, urlParam);
    }

    private HttpHeaders initHeader() {
        HttpHeaders headers = new HttpHeaders();
        if (sid != null) {
            headers.add("Cookie", "s_id=" + sid);
        }
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        return headers;
    }

    public ResponseEntity<String> postWithJson(String url, String parameterStr) {
        if (!StringUtils.isNotBlank(url)) {
            throw new IllegalArgumentException("url can not be null.");
        }
//        ObjectMapper objectMapper = new ObjectMapper();
//        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        HttpEntity<String> entity = new HttpEntity<>(parameterStr, initHeader());
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(180000);
        requestFactory.setReadTimeout(180000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        return restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
    }

    public ResponseEntity<String> get(String url) {
        if (!StringUtils.isNotBlank(url)) {
            throw new IllegalArgumentException("url can not be null.");
        }
        HttpEntity<String> httpEntity = new HttpEntity<>(initHeader());
        return restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
    }
}
posted on 2019-06-25 17:10  liehen2046  阅读(128)  评论(0编辑  收藏  举报