工具篇 -- Spring RestTemplate 工具封装

Spring RestTemplate 工具封装

http之间访问,解决乱码问题,有返回值信息。

资源引入

 

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.8.RELEASE</version>
 </dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
     <version>3.4</version>
</dependency>

工具类封装

package com.dome.utils;


import java.net.URI;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import com.alibaba.fastjson.JSONObject;
import com.ds.face.exception.HttpConnectionException;
import lombok.extern.slf4j.Slf4j;

/**
 * HTTP 请求工具类
 *
 * @author Simon
 * @date 2018年7月23日
 */

@Slf4j
public class HttpConnectionUtils {
    private HttpConnectionUtils() {
    }

    /**
     * post 请求封装
     *
     * @param value
     * @param URL
     * @return
     */

    public static JSONObject post(final Object value, final String URL) {

        if (!StringUtils.isNotBlank(URL)) {
            return null;

        }
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(Inclusion.NON_EMPTY);
        String requestJson = null;
        try {
            requestJson = objectMapper.writeValueAsString(value);

        } catch (Exception e) {

            e.printStackTrace();

        }

        log.info("requestJson:{}", requestJson);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
        SimpleClientHttpRequestFactory requestFactory = new  SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(180000);// 设置超时
        requestFactory.setReadTimeout(180000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        log.info("URL:{}", URL);
        ResponseEntity<String> response = restTemplate.exchange(URL, HttpMethod.POST, entity, String.class);
        Integer code = response.getStatusCode().value();
        if (200 != code) {

            //错误返回值处理

        }

        JSONObject body = new JSONObject().parseObject(response.getBody());
        log.info("body:{}", body);
        return body;
    }



    /**
     * get请求封装
     *
     * @param uriComponents
     * @return
     */

    public static JSONObject get(final UriComponents uriComponents) {

        if (null == uriComponents) {
           return null;

        }

        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(5000);
        requestFactory.setConnectTimeout(5000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        URI uri = uriComponents.toUri();
        log.info(uri.toString());
        ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
        Integer code = response.getStatusCode().value();
        if (200 != code) {

            //错误返回值处理

        }

        JSONObject body = new JSONObject().parseObject(response.getBody());
        log.info("body:{}", body);
        return body;

    }

    /**
     * delete请求封装
     *
     * @param URL
     * @param map
     * @return
     */

    public static JSONObject delete(final String URL,final  Map<String, Object> map) {

        if (!StringUtils.isNotBlank(URL)) {

            return null;

        }

        log.info("URL:{}", URL);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(180000);// 设置超时
        requestFactory.setReadTimeout(180000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        ResponseEntity<String> response = restTemplate.exchange(URL, HttpMethod.DELETE, entity, String.class, map);
Integer code = response.getStatusCode().value();

        if (200 != code) {

           //错误返回值处理

        }
        JSONObject body = new JSONObject().parseObject(response.getBody());
        log.info("body:{}", body);
        return body;

    }

}

测试

package com.dome.test;

import java.util.HashMap;
import java.util.Map;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import com.ds.face.utils.HttpConnectionUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:config/springmvc.xml")
public class HttpConnectionUtilsTest {

    public void delete() {
        String URL = "http://192.168.1.214:8080/server/delete?appId={appId}&dbName={dbName}";
        Map<String, Object> map = new HashMap<>();
        map.put("appId", "123");
        map.put("dbName", "test0001");
        HttpConnectionUtils.delete(URL, map);

    }

    public void get() {
        String URL = "http://192.168.1.214:8080/server/get?appId={appId}&dbName={dbName}";

        UriComponents uriComponents = UriComponentsBuilder.fromUriString(URL).build().expand("123", "test0001")
                .encode();
       HttpConnectionUtils.get(uriComponents);

    }

    public void post() {
        String URL = "http://192.168.1.214:8080/server/post";
        Dome dome = new Dome();
        dome.setAppId("123");
        dome.setDbName("test0001");
        HttpConnectionUtils.post(dome, URL);

    }
}



 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值