java中远程调用接口springboot

package com.kakarote.crm.utils;
import cn.hutool.core.util.ObjectUtil;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/**
 * create by Dell on 2020/6/17
 */
public class HttpUtil {
        //get请求
        public static String doGet(String url,String authValue){
                String result = null;
                CloseableHttpClient httpClient = HttpClients.createDefault();
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                try {
                        HttpGet httpGet = new HttpGet(url);
                        httpGet.setHeader("Content-type", "application/json");
                        if(!ObjectUtil.isNull(authValue)){
                                httpGet.setHeader("Authorization","Bearer "+authValue);
                        }
                        result = httpClient.execute(httpGet, responseHandler);
                } catch (Exception e) {
                        e.printStackTrace();
                }
                finally {
                        try {
                                httpClient.close();
                        } catch (Exception e) {
                                System.out.println(e.getMessage());
                        }
                }
                return result ;
        }

        // post请求参数为json格式
        public static String doJsonPost(String url, String json,String authValue) {
                String result = null;
                CloseableHttpClient httpClient = HttpClients.createDefault();
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                try {
                        HttpPost httpPost = new HttpPost(url);
                        StringEntity requestEntity = new StringEntity(json, "utf-8");
                        requestEntity.setContentEncoding("UTF-8");
                        httpPost.setHeader("Content-type", "application/json");
                        if(!ObjectUtil.isNull(authValue)){
                                httpPost.setHeader("Authorization","Bearer "+authValue);
                        }
                        httpPost.setEntity(requestEntity);
                        result = httpClient.execute(httpPost, responseHandler);
                } catch (Exception e) {
                        System.out.println(e.getMessage());
                } finally {
                        try {
                                httpClient.close();
                        } catch (Exception e) {
                                System.out.println(e.getMessage());
                        }
                }
                return result;
        }
}

  

package com.kakarote.crm.utils;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.kakarote.crm.constant.SapConstant;
import com.kakarote.crm.entity.authorize.Authorize;
import com.kakarote.crm.entity.authorize.Token;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;

/**
 * create by Dell on 2020/7/11
 */
@Component
public class SapUtil {
        public static String readUrl ;
        public static String readPort ;
        public static String readUsername ;
        public static String readPassword;
        public static String writeUrl ;
        public static String writePort ;
        public static String writeUsername ;
        public static String writePassword;

        @Value("${sap.api.read.url}")
        public void setReadUrl(String readUrl){
                SapUtil.readUrl = readUrl;
        }
        @Value("${sap.api.read.port}")
        private void setReadPort(String readPort){
                SapUtil.readPort = readPort;
        }
        @Value("${sap.api.read.username}")
        public void setReadUsername(String readUsername) {
                SapUtil.readUsername = readUsername;
        }
        @Value("${sap.api.read.password}")
        public void setReadPassword(String readPassword) {
                SapUtil.readPassword = readPassword;
        }
        @Value("${sap.api.write.url}")
        public void setWriteUrl(String writeUrl) {
                SapUtil.writeUrl = writeUrl;
        }
        @Value("${sap.api.write.port}")
        public void setWritePort(String writePort) {
                SapUtil.writePort = writePort;
        }
        @Value("${sap.api.write.username}")
        public void setWriteUsername(String writeUsername) {
                SapUtil.writeUsername = writeUsername;
        }
        @Value("${sap.api.write.password}")
        public void setWritePassword(String writePassword) {
                SapUtil.writePassword = writePassword;
        }

        private static String readToken = "";
        private static long readCreateDate = 0l;

        private static String writeToken ="";
        private static long writeCreateDate = 0l ;

        public static String getReadToken(){
                if("".equals(readToken) || ObjectUtil.isNull(readToken) || ObjectUtil.isNull(readToken)){
                        return getReadToken(readUsername,readPassword);
                }
                else{
                        if(new Date().getTime() - readCreateDate >= 43000000l ){
                                return getReadToken(readUsername,readPassword);
                        }
                }
                return readToken;
        }

        public static String getWriteToken(){
                if("".equals(writeToken) || ObjectUtil.isNull(writeToken) || ObjectUtil.isNull(writeToken)){
                        return getWriteToken(writeUsername,writePassword);
                }
                else{
                        if(new Date().getTime() - writeCreateDate >= 43000000l ){
                                return getWriteToken(writeUsername,writePassword);
                        }
                }
                return writeToken;
        }

        public static String getReadToken(String username,String password){
                Authorize auth = new Authorize();
                auth.setUsername(username);
                auth.setPassword(password);
                try {
                        String res = HttpUtil.doJsonPost(SapConstant.READ_LOGIN_AUTHORIZE, JSONObject.toJSONString(auth),null);
                        if(!ObjectUtil.isNull(res)&&!ObjectUtil.isNull(res)){
                                Token token = JSONObject.parseObject(res, Token.class);
                                readToken=token.getToken();
                                readCreateDate = new Date().getTime();
                        }
                }
                catch(Exception e){
                        // TODO
                }
                return readToken;
        }

        public static String getWriteToken(String username,String password){
                Authorize auth = new Authorize();
                auth.setUsername(username);
                auth.setPassword(password);
                try {
                        String res = HttpUtil.doJsonPost(SapConstant.WRITE_LOGIN_AUTHORIZE, JSONObject.toJSONString(auth),null);
                        if(!ObjectUtil.isNull(res)&&!ObjectUtil.isNull(res)){
                                Token token = JSONObject.parseObject(res, Token.class);
                                writeToken=token.getToken();
                                writeCreateDate = new Date().getTime();
                        }
                }
                catch(Exception e){
                        // TODO
                }
                return writeToken;
        }

}

  

package com.kakarote.crm.constant;
import com.kakarote.crm.utils.SapUtil;
/**
 * 
 */
public interface SapConstant {

        String READ_LOGIN_AUTHORIZE = SapUtil.readUrl+":"+SapUtil.readPort+"/api/login/authorize";
        String WRITE_LOGIN_AUTHORIZE = SapUtil.writeUrl+":"+SapUtil.writePort+"/api/login/authorize";

        String PARTNER_INIT = SapUtil.readUrl+":"+SapUtil.readPort+"/api/partner/init?Company={0}&CardType={1}";
        String PARTNER_DETAIL = SapUtil.readUrl+":"+SapUtil.readPort+"/api/partner/detail?Company={0}&CardCode={1}";
        String PARTNER_QUERY = SapUtil.readUrl+":"+SapUtil.readPort+"/api/partner/query?Company={0}&CardType={1}&Partner={2}";
        String PARTNER_SPECPRICES_DETAIL = SapUtil.readUrl+":"+SapUtil.readPort+"/api/partner/specprices/detail?Company={0}&CardCode={1}";
        
}

  yml文件配置

spring:
  redis:
    host: ${REDIS_HOST:localhost}
    port: ${REDIS_PORT:6379}
    password: ${REDIS_PASSWORD:xxxxx}
    database: 13
    lettuce:
      pool:
        max-active: 300
  datasource:
    url: jdbc:${DATASOURCE_DBTYPE:mysql}://${DATASOURCE_HOST:127.0.0.1}:${DATASOURCE_PORT:3306}/wk_crm_single?characterEncoding=utf8&useSSL=false&zeroDateTimeBehavior=convertToNull&tinyInt1isBit=false&serverTimezone=Asia/Shanghai
    username: ${DATASOURCE_USERNAME:root}
    password: ${DATASOURCE_PASSWORD:xxxx}
  elasticsearch:
    rest:
      uris: 127.0.0.1:xx00
      username:
      password:
#sap配置
sap:
  api:
    read:
      url: http://172.19.xxx.xx
      port:  xxxx
      username: admin
      password: xxxx
    write:
      url: http://172.19.xxx.xx
      port: xxxx
      username: admin
      password: xxxx

  

package com.kakarote.crm.entity.authorize;

import lombok.Data;

/**
 * create by Dell on 2020/7/13
 */
@Data
public class Authorize {
        private String username ;
        private String password ;
}

  

package com.kakarote.crm.entity.authorize;

import lombok.Data;

/**
 * create by Dell on 2020/7/13
 */
@Data
public class Token {
        private String token;
}

  

package com.kakarote.crm.controller.sap;
import com.alibaba.fastjson.JSONObject;
import com.kakarote.crm.constant.SapConstant;
import com.kakarote.crm.utils.HttpUtil;
import com.kakarote.crm.utils.SapUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.MessageFormat;
import java.util.Map;

/**
 * @author 
 * @date 2020/11/18
 */
@Slf4j
@RestController
@RequestMapping("/sapProduct")
@Api(tags = "查询sap产品")
public class SapProductController {
    @GetMapping("/init")
    public Map<String,Object> init(String company, String cardType) {
        company="SP";
        cardType="S";
        String url = MessageFormat.format(SapConstant.PARTNER_INIT,company,cardType);
        log.info("url==========="+url+"----token====="+ SapUtil.getReadToken());
        String res = HttpUtil.doGet(url, SapUtil.getReadToken());
        Map<String,Object> result = JSONObject.parseObject(res, Map.class);
        log.info("查询字段列表============result====="+result);
        return result;
    }
}