zoukankan      html  css  js  c++  java
  • spring rest 请求怎样添加Basic Auth请求頭

    请自行揣摩代码

    package com.hudai.platform.manager.util;
    
    import java.net.URI;
    import java.net.URISyntaxException;
    
    import javax.annotation.Resource;
    
    import org.apache.commons.codec.binary.Base64;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.http.RequestEntity;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Component;
    import org.springframework.web.client.RestTemplate;
    
    import com.alibaba.fastjson.JSONObject;
    import com.hudai.platform.manager.config.BaseEnum;
    import com.hudai.platform.manager.model.BaseResponse;
    
    /**
     * @author WanHongLei
     * @version 创建时间:2019年2月19日 下午3:09:13 类说明
     */
    @Component
    public class RestApi {
        private static final Logger logger = LoggerFactory.getLogger(RestApi.class);
    
        @Resource
        private RestTemplate restTemplate;
        
        @Value("${xjd.applications.url}")
        private String url;
        
        @Value("${clientCredentials}")
        private String clientCredentials;
    
        public BaseResponse<JSONObject> proxy(Object obj, String path) {
            URI uri;
            try {
                uri = new URI(url + path);
            } catch (URISyntaxException e) {
                logger.error("URI构建失败", e);
                return new BaseResponse<>(BaseEnum.FAILED.getCode(), BaseEnum.FAILED.getName());
            }
    
            String base64ClientCredentials = new String(Base64.encodeBase64(clientCredentials.getBytes()));
            
            RequestEntity<Object> requestEntity = RequestEntity.post(uri).header("Authorization", "Basic " + base64ClientCredentials).contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON).body(obj);
            ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(requestEntity, JSONObject.class);
            JSONObject jsonObj = responseEntity.getBody();
            if(responseEntity.getStatusCode() == HttpStatus.OK){
                return new BaseResponse<>(jsonObj);
            }else{
                logger.error("请求失败,errmsg = " + jsonObj.toJSONString());
                return new BaseResponse<>(jsonObj.getIntValue("error"), jsonObj.getString("msg"));
            }
        }
    }

     application.properties中添加:clientCredentials=user:password

  • 相关阅读:
    mac下编写命令脚本
    mac环境mongodb安装小坑
    JS
    设计模式:装饰器
    proxy 数据帧听
    react hook 简单实现
    报错:java.lang.NumberFormatException: null
    git回滚到指定版本
    1109. 航班预订统计 力扣(中等) 差分数组 不会但神奇
    528. 按权重随机选择 力扣(中等) 前缀和rand()
  • 原文地址:https://www.cnblogs.com/Mr-Rocker/p/10402641.html
Copyright © 2011-2022 走看看