栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot使用RestTemplate发网络请求

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot使用RestTemplate发网络请求

SpringBoot使用RestTemplate发网络请求 依赖
    
        
            org.junit.jupiter
            junit-jupiter-engine
            test
        
        
            org.junit.vintage
            junit-vintage-engine
            test
        

        
        
            org.junit.platform
            junit-platform-launcher
            test

        
        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

  
        
            com.alibaba
            fastjson
            1.2.41
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
            junit
            junit
            test
        

        
            com.alibaba
            druid-spring-boot-starter
            1.1.22
        
        
            org.springframework.boot
            spring-boot-starter-aop
            2.1.4.RELEASE
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.apache.commons
            commons-lang3
            3.4
        
        
            io.springfox
            springfox-oas
            3.0.0
            compile
        
        
            org.apache.httpcomponents
            httpclient
            4.5.6
        

    
配置类
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

@Slf4j
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate()
    {
        ClientHttpRequestFactory requestFactory = null;
        try {
            requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient());
        } catch (Exception e) {
            log.error("init ClientHttpRequestFactory error.",e);
        }
        return new RestTemplate(requestFactory);
    }

    
    private HttpClient httpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(1000*100) // 服务器返回数据(response)的时间,超时抛出read timeout
            .setConnectTimeout(1000*100) // 连接上服务器(握手成功)的时间,超时抛出connect timeout
            .setConnectionRequestTimeout(1000)// 从连接池中获取连接的超时时间,超时抛出ConnectionPoolTimeoutException
            .build();
        SSLContext sslContext = SSLContextBuilder.create().setProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
        return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).
            setSSLContext(sslContext)
            .setMaxConnTotal(200)
            .setMaxConnPerRoute(200).setSSLHostnameVerifier((x, y) -> true).build();
    }

}
工具类
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@Component
@Slf4j
public class RestTemplateUtil {

    @Autowired
    RestTemplate restTemplate;


    public  T post(String url, Object messageInfo, HttpHeaders headers,Class tClass) {
        log.info("url:{},messageInfo:{}", url, messageInfo);
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity entity = new HttpEntity(messageInfo, headers);
        ResponseEntity responseEntity = restTemplate.postForEntity(url, entity, tClass);
        log.info("result:{}", responseEntity.getBody());
        return responseEntity.getBody();
    }

    public  T postObject(String url, Object messageInfo,Class tClass) {
        log.info("url:{},messageInfo:{}", url, messageInfo);
        HttpEntity entity = new HttpEntity(JSONObject.toJSONString(messageInfo));
        ResponseEntity responseEntity = restTemplate.postForEntity(url, entity, tClass);
        log.info("result:{}", responseEntity.getBody());
        return responseEntity.getBody();
    }

    public  T getForObject(String url,Class tClass){
        log.info("url:{}",url);
        T forObject = restTemplate.getForObject(url
                , tClass);
        log.info("result:{}",forObject);
        return forObject;
    }

    public  T exchange(String url,Class tClass){
        HttpHeaders headers = new HttpHeaders();
        headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        HttpEntity httpEntity = new HttpEntity(headers);
        ResponseEntity resp = restTemplate.exchange(url, HttpMethod.GET, httpEntity, tClass);
        return resp.getBody();
    }

    public  T exchangeHeader(String url,Class tClass,HttpHeaders headers){
        log.info("url:{}",url);
        HttpEntity httpEntity = new HttpEntity(headers);
        ResponseEntity resp;
        try {
            resp = restTemplate.exchange(url, HttpMethod.GET, httpEntity, tClass);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return resp.getBody();
    }

    public  T exchange(String url,Class tClass, Map param){
        HttpHeaders headers = new HttpHeaders();
        headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        HttpEntity httpEntity = new HttpEntity(headers);

        ResponseEntity resp = restTemplate.exchange(url, HttpMethod.GET, httpEntity, tClass,param);
        return resp.getBody();
    }

    public  T exchangeNoHeader(String url,Class tClass, Map param){
        HttpHeaders headers = new HttpHeaders();
        //headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        HttpEntity httpEntity = new HttpEntity(headers);
        ResponseEntity resp = restTemplate.exchange(url, HttpMethod.GET, httpEntity, tClass,param);
        return resp.getBody();
    }

    public  void showBytes(String url, HttpServletResponse httpServletResponse) {
        HttpHeaders headers = new HttpHeaders();
        HttpEntity httpEntity = new HttpEntity(headers);
        httpServletResponse.setHeader("Content-Disposition", "inline;");
        httpServletResponse.setContentType("image/jpeg");
        //如果返回的是String 则改用 String 若为文件流 则改用 Resource
        ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity,Resource.class);
        if (responseEntity.getStatusCodeValue()!= HttpStatus.OK.value()){
            return ;
        }
        if (responseEntity != null) {
                InputStream responseInputStream=null;
                try {
                    responseInputStream = responseEntity.getBody().getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (responseInputStream == null) {
                    return ;
                } else {
                    try {
                        OutputStream outputStream = httpServletResponse.getOutputStream();
                        outputStream.write(toByteArray(responseInputStream));
                        outputStream.flush();
                        outputStream.close();
                        return ;
                    } catch (IOException e) {
                        log.error("图片数据转化为byte[]失败");
                        return ;
                    }
                }
        }
        return ;
    }
    public  byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*4];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

}

 
使用与测试 
YourRetuenObject res=new YourRetuenObject();
        String url="your url";
//        设置header
        HttpHeaders httpHeaders=new HttpHeaders();
        httpHeaders.add("X-Accept","application/json");
        httpHeaders.add("Accept-Encoding","deflate, gzip");

        JSONObject result = null;
        try{
            // 发起请求
            result = restTemplateUtil.exchangeHeader(url, JSONObject.class,httpHeaders);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        Integer ret = -1;
        if (result!=null){
            // 获取返回值
            ret = (Integer)((LinkedHashMap)result.get("status")).get("error_code");
        }

//       请求成功,解析数据
        if (ret==0){
            Collection data = ((LinkedHashMap) result.get("data")).values();
            for (Object datum : data) {
                JSONObject json = (JSONObject) JSON.toJSON(datum);
                if (json!=null){
//                    基本信息
                    res.setSymbol(json.getString("symbol"));
                    res.setCoinLogo(json.getString("logo"));
//                    设置社交网络信息
                    JSONObject urls = json.getJSONObject("urls");
                    if(urls!=null){
                        res.setOfficialWebsite( urls.getJSONArray("website").get(0).toString());
                        res.setTwitter( urls.getJSONArray("twitter").get(0).toString());
                    }

                }
            }
        }

        return res;
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号