怎么调用别人接口?

Posted 莒县程序猿

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了怎么调用别人接口?相关的知识,希望对你有一定的参考价值。

目录

前言

一、怎么调用别人接口?

二、使用步骤

1.配置restTemplateConfig

2.自己测试一下

总结



前言

工作中调别人接口拿数据必不可少 应该怎么取拿呢


提示:确实是非常非常的简单~~~~~

一、怎么调用别人接口?

往下看~~~~~

二、使用步骤

1.配置restTemplateConfig

不配置用不了!!!!:

@Configuration
public class restTemplateConfig 
    private static final Logger logger= LoggerFactory.getLogger(restTemplateConfig.class);

    @Bean
    public RestTemplate restTemplate() 
        // 添加内容转换器,使用默认的内容转换器
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
        // 设置编码格式为UTF-8
        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
        HttpMessageConverter<?> converterTarget = null;
        for (HttpMessageConverter<?> item : converterList) 
            if (item.getClass() == StringHttpMessageConverter.class) 
                converterTarget = item;
                break;
            
        
        if (converterTarget != null) 
            converterList.remove(converterTarget);
        
        HttpMessageConverter<?> converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
        converterList.add(1,converter);

        return restTemplate;
    

    @Bean
    public ClientHttpRequestFactory httpRequestFactory() 

        return new HttpComponentsClientHttpRequestFactory(httpClient());

    

    @Bean
    public HttpClient httpClient() 
        // 长连接保持30秒
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
        //设置整个连接池最大连接数 根据自己的场景决定
        connectionManager.setMaxTotal(500);
        //同路由的并发数,路由是对maxTotal的细分
        connectionManager.setDefaultMaxPerRoute(500);

        //requestConfig
        RequestConfig requestConfig = RequestConfig.custom()
                //服务器返回数据(response)的时间,超过该时间抛出read timeout
                .setSocketTimeout(10000)
                //连接上服务器(握手成功)的时间,超出该时间抛出connect timeout
                .setConnectTimeout(5000)
                //从连接池中获取连接的超时时间,超过该时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
                .setConnectionRequestTimeout(500)
                .build();
        //headers
        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
        headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
        headers.add(new BasicHeader("Accept-Language", "zh-CN"));
        headers.add(new BasicHeader("Connection", "Keep-Alive"));
        headers.add(new BasicHeader("Content-type", "application/json;charset=UTF-8"));

        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .setDefaultHeaders(headers)
                // 保持长连接配置,需要在头添加Keep-Alive
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
                //重试次数,默认是3次,没有开启
                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, true))
                .build();
    
    @Bean
    public RestTemplate customRestTemplate()
        HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpComponentsClientHttpRequestFactory.setConnectionRequestTimeout(10);
        httpComponentsClientHttpRequestFactory.setConnectTimeout(10);
        httpComponentsClientHttpRequestFactory.setReadTimeout(10);

        return new RestTemplate(httpComponentsClientHttpRequestFactory);
    

2.自己测试一下

//junit 测试~~~~

public class test 

    @Autowired
    RestTemplate restTemplate;

    @Test
    public void get()throws Exception 
        String url = "http://localhost/xxx/xxx?id=id";
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("id", 1);
        String result1 = restTemplate.getForObject(url, String.class, paramMap);
        System.out.println("result1====================" + result1);
//如果添加请求头什么的用下面这个
/*
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(null,headers);
        ResponseEntity<String> response2 = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class,paramMap);
        System.out.println("result2====================" + response2.getBody());*/
    

二、第二种办法

public class HttpPostUtil 

    /**
     * 模拟浏览器的请求
     *
     * @param httpURL 发送请求的地址
     * @param params  请求参数
     * @return
     * @throws Exception
     */
    public static String sendHttpRequest(String httpURL, Map<String, String> params) throws Exception 
        //建立URL连接对象
        URL url = new URL(httpURL);
        //创建连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求的方式(需要是大写的)
        conn.setRequestMethod("POST");
        //设置需要输出
        conn.setDoOutput(true);
        //判断是否有参数.
        if (params != null && params.size() > 0) 
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) 
                sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            
            //sb.substring(1)去除最前面的&
            conn.getOutputStream().write(sb.substring(1).toString().getBytes("utf-8"));
        
        //发送请求到服务器
        conn.connect();
        //获取远程响应的内容.
        String responseContent = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("utf-8"));
        conn.disconnect();
        return responseContent;
    

    /**
     * 模拟浏览器的请求
     *
     * @param httpURL    发送请求的地址
     * @param jesssionId 会话Id
     * @return
     * @throws Exception
     */
    public static void sendHttpRequest(String httpURL, String jesssionId) throws Exception 
        //建立URL连接对象
        URL url = new URL(httpURL);
        //创建连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求的方式(需要是大写的)
        conn.setRequestMethod("POST");
        //设置需要输出
        conn.setDoOutput(true);
        conn.addRequestProperty("Cookie", "JSESSIONID=" + jesssionId);
        //发送请求到服务器
        conn.connect();
        conn.getInputStream();
        conn.disconnect();
    

    public static String sendCadreIdHttpRequest(String httpURL) throws Exception 
        //建立URL连接对象
        URL url = new URL(httpURL);
        //创建连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求的方式(需要是大写的)
        conn.setRequestMethod("POST");
        //设置需要输出
        conn.setDoOutput(true);
        //发送请求到服务器
        conn.connect();
        //获取远程响应的内容.
        String responseContent = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("utf-8"));
        conn.disconnect();
        return responseContent;
    

    public static String sendCadreIdHttpRequestGET(String httpURL) throws Exception 
        //建立URL连接对象
        URL url = new URL(httpURL);
        //创建连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求的方式(需要是大写的)
        conn.setRequestMethod("GET");
        //设置需要输出
        conn.setDoOutput(true);
        //发送请求到服务器
        conn.connect();
        //获取远程响应的内容.
        String responseContent = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("utf-8"));
        conn.disconnect();
        return responseContent;
    

 


    public List<User> getUser(String cadreId) 
        //参数
        Map<String, String> map = new HashMap<>();
        map.put("woshicanshu", "canshu");
        List<User> letterList = new ArrayList<>();
        try 
            String json = HttpPostUtil.sendHttpRequest("http://127.0.0.1:8080/user/getUser", map);
            if (StringUtils.isNotEmpty(json)) 
                ArrayList<User> users= JSON.parseObject(json, new TypeReference<ArrayList<User>>() 
                );
                return users;
            

            return users;

         catch (Exception e) 
            e.printStackTrace();
            return users;
        
    

总结

调别人接口贼简单 这是GET请求 Post就把restTemplate.getForObject改成restTemplate.PostForObject  是不是贼简单~~~~

以上是关于怎么调用别人接口?的主要内容,如果未能解决你的问题,请参考以下文章

怎么调用别人接口?

怎么调用别人接口?

怎么调用别人接口?

别人写了一个用SHA1加密的接口,请问我怎么调用它啊?

Python如何调用别人写好的脚本

java给别人提供接口,接口安全怎么保证