The use of RestTemplate and the points to pay attention to

 

The use of RestTemplate and the points to pay attention to

 

 

1. Contains generic objects, pay attention to whether the list is returned or a single entity. The returned list needs to be wrapped with ParameterizedTypeReference, that is, it will be recognized as a composite class after wrapping, and will not be resolved as a single class

Otherwise Json exception: Can not deserialize instance of xx out of START_ARRAY token cannot be converted exception

 

 ParameterizedTypeReference<List<FinancialSalesUser>> responseType = new ParameterizedTypeReference<List<FinancialSalesUser>>() {

            @Override

            public Type getType() {

               return super.getType();

            }

        };

public class BaseResponseInterface<T> implements Serializable 
ParameterizedTypeReference<BaseResponseInterface<FinancialInterfaceAccount>> responseType = new ParameterizedTypeReference<BaseResponseInterface<FinancialInterfaceAccount>>() {
    @Override
    public Type getType() {
        return super.getType();
    }

}; 

 

2. Note that the request parameter entity is placed in HttpEntity

 HttpEntity<String> httpEntity = new HttpEntity<String>(bodyData, headers);//bodyData参数,headers报文头

HttpEntity<FinancialInterfaceBaseCondition> httpEntity = new HttpEntity<FinancialInterfaceBaseCondition>(bc, headers);

 The body in the HttpEntity is taken from the body with @RequestBody, and the last parameter is @RequestParam or @PathVariable

Returns the entity as the class that follows

 

3. The parameters of the object map type are placed at the end and can not be passed

 

 

4. It is best to use exchange as a unified operation, and some other methods can only be limited by a single entity.

 

 

 

 

Example:

 

configure

 

 <!--Use httpclient implementation, with connection pool -->

    <!--Only after httpclient4.3 version-->

    <bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create">

        <property name="connectionManager">

            <bean class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">

                <!--Concurrency of the entire connection pool-->

                <property name="maxTotal" value="50"/>

                <!--Concurrency per host -->

                <property name="defaultMaxPerRoute" value="50"/>

            </bean>

        </property>

        <!--Open retry-->

        <property name="retryHandler">

            <bean class="org.apache.http.impl.client.DefaultHttpRequestRetryHandler">

                <constructor-arg value="2"/>

                <constructor-arg value="true"/>

            </bean>

        </property>

        <property name="defaultHeaders">

            <list>

                <bean class="org.apache.http.message.BasicHeader">

                    <constructor-arg value="Content-Type"/>

                    <constructor-arg value="text/html;charset=UTF-8"/>

                </bean>

                <bean class="org.apache.http.message.BasicHeader">

                    <constructor-arg value="Accept-Encoding"/>

                    <constructor-arg value="gzip,deflate"/>

                </bean>

                <bean class="org.apache.http.message.BasicHeader">

                    <constructor-arg value="Accept-Language"/>

                    <constructor-arg value="zh-CN"/>

                </bean>

            </list>

        </property>

    </bean>

 

    <bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build"/>

 

     <bean id="restTemplate1" class="org.springframework.web.client.RestTemplate">

        <property name="messageConverters">

            <list value-type="org.springframework.http.converter.HttpMessageConverter">

                <bean class="org.springframework.http.converter.StringHttpMessageConverter">

                    <property name="supportedMediaTypes">

                        <value>text/html;charset=UTF-8</value>

                    </property>

                </bean>

                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">

                    <property name="supportedMediaTypes">

                        <value>application/json;charset=UTF-8</value>

                    </property>

                </bean>

                <bean class="org.springframework.http.converter.ResourceHttpMessageConverter"/>

                <bean class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter"/>

                <bean class="org.springframework.http.converter.FormHttpMessageConverter"/>

                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>//This is consistent with springmvc

            </list>

        </property>

        <property name="requestFactory">

            <bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">

                <constructor-arg ref="httpClient"/>

                <!--Connection time (milliseconds)-->

                <property name="connectTimeout" value="20000"/>

                <!--Read time (milliseconds)-->

                <property name="readTimeout" value="20000"/>

            </bean>

        </property>

    </bean>

 

 

 

Code:

 

package com.houbank.incoming.web.controller;

 

import com.alibaba.dubbo.config.annotation.Reference;

import com.houbank.basic.util.page.Pagination;

import com.houbank.basic.util.response.BaseResponse;

import com.houbank.incoming.api.FinancialSalesUserFacade;

import com.houbank.incoming.model.condition.FinancialSalesUserCondition;

import com.houbank.incoming.model.domain.FinancialSalesUser;

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;

import io.swagger.annotations.ApiResponse;

import io.swagger.annotations.ApiResponses;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections.CollectionUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.core.ParameterizedTypeReference;

import org.springframework.http.*;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.client.RestTemplate;

 

import java.lang.reflect.Type;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

/**

 * @author: yy  Date: 2018/3/26 Time: 14:26

 */

 

@Controller

@ Slf4j

@RequestMapping({ "/FinancialInterfaceAccountInfo" })

@Api(value="/FinancialInterfaceAccountInfo",description="Account Information")

public class FinancialInterfaceAccountInfoController {

 

    @Autowired

    private RestTemplate restTemplate1;

 

    @Reference

    private FinancialSalesUserFacade financialSalesUserFacade;

 

    @RequestMapping(value = { "/hygiene" }, method = RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)

    @ResponseBody

    public Map hygiene() {

        Map<String,String> result = new HashMap<String,String>();

        try {

            result.put("11","22");

            result.put("21","23");

        }catch (Exception e) {

            e.printStackTrace ();

        }

 

        return result;

    }

 

    @RequestMapping(value = "/RateQuery/result", method = RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)

    public @ResponseBody FinancialSalesUser getRatedefQueryResult (FinancialSalesUser resultRatedtl) {

        BaseResponse <List <FinancialSalesUser>> baseResponse = new BaseResponse <List <FinancialSalesUser>> ();

        try {

            FinancialSalesUserCondition financialSalesUserCondition = new FinancialSalesUserCondition();

            baseResponse = financialSalesUserFacade.selectAll(financialSalesUserCondition);

        }catch (Exception e) {

            log.error("error"+e);

        }

        return baseResponse.getData().get(0);

    }

 

    @RequestMapping(value = "/RateQuery/results", method = RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)

    public @ResponseBody List <FinancialSalesUser> getRatedefQueryResults (FinancialSalesUser resultRatedtl) {

        BaseResponse <List <FinancialSalesUser>> baseResponse = new BaseResponse <List <FinancialSalesUser>> ();

        try {

            FinancialSalesUserCondition financialSalesUserCondition = new FinancialSalesUserCondition();

            baseResponse = financialSalesUserFacade.selectAll(financialSalesUserCondition);

        }catch (Exception e) {

            log.error("error"+e);

        }

        return baseResponse.getData();

    }

 

    @ResponseBody

    @RequestMapping(value = { "/test" }, method = RequestMethod.GET,produces="application/json;charset=UTF-8")

    @ApiResponses(value = {@ApiResponse(code = 200, message = "用户信息test",  response=String.class),

            @ApiResponse(code = 201, message = "q"+ "(token验证失败)",  response=String.class),

            @ApiResponse(code = 202, message = "500" + "(system error)", response = String.class)})

    @ApiOperation(value="query list",notes="/list",response = String.class)

    public ResponseEntity<List<FinancialSalesUser>>  getTestInfo() {

//        ResponseEntity<FinancialSalesUser> str = restTemplate1.getForEntity(

//                "http://localhost:8080/hb_phonebank_web/FinancialInterfaceAccountInfo/RateQuery/result",

//                FinancialSalesUser.class);

        ParameterizedTypeReference<List<FinancialSalesUser>> responseType = new ParameterizedTypeReference<List<FinancialSalesUser>>() {

            @Override

            public Type getType() {

               return super.getType();

            }

        };

        ResponseEntity<List<FinancialSalesUser>> str = restTemplate1.exchange(

                "http://localhost:8080/hb_phonebank_web/FinancialInterfaceAccountInfo/RateQuery/results",

                HttpMethod.GET,null, responseType);

        System.out.println(str);

        return  str;

    }

 

 

 

    @ResponseBody

    @RequestMapping(value = { "/list" }, method = RequestMethod.GET,produces="application/json;charset=UTF-8")

    @ApiResponses(value = {@ApiResponse(code = 200, message = "用户信息",  response=String.class),

            @ApiResponse(code = 201, message = "q"+ "(token验证失败)",  response=String.class),

            @ApiResponse(code = 202, message = "500" + "(system error)", response = String.class)})

    @ApiOperation(value="query list",notes="/list",response = String.class)

    public Pagination<FinancialSalesUser> getAccountInfo() {

        String q="";

        BaseResponse <List <FinancialSalesUser>> baseResponse = new BaseResponse <List <FinancialSalesUser>> ();

        String remoteUrl;

        ResponseEntity<Pagination> result =null;

        try {

 

            /**

             * Set the request header

             */

            HttpHeaders headers = new HttpHeaders();

            headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));

            headers.add("Accuept", MediaType.APPLICATION_JSON.toString());

 

            /**

             * POST request parameters, encapsulated as needed

             */

            String bodyData = "";//new String(Base64Utils.encode(JSON.toJSONString(ro).getBytes("UTF-8")));

 

            /**

             * View the construction method of HttpEntity, including only the request header and only the request body---request entity parameters

             */

            HttpEntity<String> httpEntity = new HttpEntity<String>(bodyData, headers);

 

            /**

             * perform action

             */

            FinancialSalesUserCondition cd = new FinancialSalesUserCondition();

            remoteUrl="http://localhost:8080/hb_phonebank_web/financialSalesUser/listPage";

            result = restTemplate1.postForEntity(remoteUrl,httpEntity,Pagination.class);

 

                if (baseResponse != null && CollectionUtils.isNotEmpty(baseResponse.getData())) {

            }

        } catch (Exception e) {

            log.error("error"+e);

        }

 

        return result.getBody();

    }

 

}

 

 

See:

https://blog.csdn.net/ThinkingLink/article/details/45366777 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326027438&siteId=291194637