RestTemplate 工具类

通过工具类的静态方法,将RestTemplate的初始化写成静态块,直接提供方法使用

package com.cec.park.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cec.park.module.dto.sys.SubsystemConfigDto;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author zhy
 * @title: HttpClientUtil
 * @projectName car_park
 * @description: http连接工具类
 * @date 2019/10/2219:23
 */
public class HttpClientUtil {
    static RestTemplate restTemplate;

    static{
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        restTemplate = new RestTemplate(factory);
    }
    public static JSONObject doPostByJson(String url, JSONObject postData){
        JSONObject json = new JSONObject();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<JSONObject> request = new HttpEntity<>(postData, headers);
        ResponseEntity<String> response = null;
        String responseBody = "";
        try {
            response = restTemplate.postForEntity( url, request , String.class );
            responseBody = new String(response.getBody().getBytes("ISO8859-1"),"utf-8");
        } catch (RestClientException clientExp){//请求出错
            clientExp.printStackTrace();
            json.put("code",clientExp.getMessage());
            json.put("data",responseBody);
            json.put("message",clientExp.getMessage());
            json.put("result",false);
            return json;
        }catch (UnsupportedEncodingException encodingExp) {//转码出错
            json.put("code","500");
            json.put("data","结果集转码错误");
            json.put("message","结果集转码错误");
            json.put("result",false);
            return json;
        }

        //解析结果集
        JSONObject jsonObject = JSON.parseObject(responseBody);
        json.put("code",jsonObject.get("code"));
        json.put("data",jsonObject.get("data"));
        json.put("message",jsonObject.get("message"));
        json.put("result",jsonObject.get("result"));
        return json;
    }


}

直接通过工具类调用doPost。我这里是用json方式请求数据的,还可以自己添加不同的请求方式。RestTemplate是支持restful风格的请求方式的

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容