1.调用REST服务-使用代理

一、添加依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

二、代码实现

与测试

主要文件就是写一个controller用于测试,其中数据存储用到的是缓存里的EhCache,数据库使用的是jpa方式具体代码请参考cache/EhCache章节和Spring-data-jpa章节

controller/RestDemoController.java

package com.shuju.test2.controller;

import java.util.Date;

import com.shuju.test2.bean.DemoUserLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.JsonNode;
import com.shuju.test2.cache.DemoUserLogCache;

@RestController
@RequestMapping(value = "/rest", method = RequestMethod.POST)
public class RestDemoController {

    @Autowired
    private DemoUserLogCache DemoUserLogCache;

    @RequestMapping(value = "/update")
    public DemoUserLog update(@RequestBody JsonNode jsonNode) {
        System.out.println("jsonNode=" + jsonNode);
        DemoUserLog bean = DemoUserLogCache.selectById(jsonNode.get("id").asInt(1));
        if(bean == null){
            bean = new DemoUserLog();
        }
        bean.setUserName("测试");
        bean.setCreateTime(new Date());
        bean.setUserIp("192.168.1.1");
        DemoUserLogCache.updateById(bean);
        return bean;
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public DemoUserLog update2(@PathVariable(value = "id") Integer id) {
        DemoUserLog bean = DemoUserLogCache.selectById(id);
        if(bean == null){
            bean = new DemoUserLog();
        }
        bean.setUserName("测试");
        bean.setCreateTime(new Date());
        bean.setUserIp("192.168.1.1");
        DemoUserLogCache.updateById(bean);
        return bean;
    }

}

启动服务,默认端口为8080

修改测试类测试

package com.shuju.test2;


import com.shuju.test2.bean.DemoUserLog;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.HashMap;
import java.util.Map;


@RunWith(SpringRunner.class)
@SpringBootTest
public class Test2ApplicationTests {

    @Autowired
    private RestTemplateBuilder restTemplateBuilder;

    /**
     * get请求
     */
    @Test
    public void getForObject() {
        DemoUserLog bean = restTemplateBuilder.build().getForObject("http://localhost:8080/rest/update/{id}", DemoUserLog.class, 1);
        System.out.println(bean);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id", 1);
        bean = restTemplateBuilder.build().postForObject("http://localhost:8080/rest/update", map, DemoUserLog.class);
        System.out.println(bean);
    }
}

四、代理实现

直接修改测试类,一般开发时写成工具类

package com.shuju.test2;


import com.shuju.test2.bean.DemoUserLog;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.protocol.HttpContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


@RunWith(SpringRunner.class)
@SpringBootTest
public class Test2ApplicationTests {

    @Autowired
    private RestTemplateBuilder restTemplateBuilder;

    /**
     * get请求
     */
    @Test
    public void getForObject() {
        /*DemoUserLog bean = restTemplateBuilder.build().getForObject("http://localhost:8080/rest/update/{id}", DemoUserLog.class, 1);
        System.out.println(bean);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id", 1);
        bean = restTemplateBuilder.build().postForObject("http://localhost:8080/rest/update", map, DemoUserLog.class);
        System.out.println(bean);*/


        String result = restTemplateBuilder.additionalCustomizers(new ProxyCustomizer()).build().getForObject("http://www.baidu.com", String.class);
        System.out.println(result);

    }

    static class ProxyCustomizer implements RestTemplateCustomizer {
        @Override
        public void customize(RestTemplate restTemplate) {
            String proxyHost = "140.206.132.118";
            int proxyPort = 8060;

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            HttpClient httpClient = HttpClientBuilder.create().setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {
                @Override
                public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException {

                    return super.determineProxy(target, request, context);
                }
            }).build();
            HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
            httpComponentsClientHttpRequestFactory.setConnectTimeout(10000);
            httpComponentsClientHttpRequestFactory.setReadTimeout(60000);
            restTemplate.setRequestFactory(httpComponentsClientHttpRequestFactory);
        }
    }
}

在线代理ip地址:

http://ip.zdaye.com/

Last updated