精华内容
下载资源
问答
  • spring cloud 微服务之间添加自定义的header头spring cloud 微服务之间添加自定义的header头创建注册中心创建生产者创建消费者验证结果 spring cloud 微服务之间添加自定义的header头 在我们的微服务开发过程中,有...

    spring cloud 微服务之间添加自定义的header头

    在我们的微服务开发过程中,有时候我们在调用其他微服务的时候,我们希望把一些参数放在header中,而不是作为参数往下传,这样的场景我们该如何解决呢?

    创建注册中心

    首先我们使用IDEA创建一个空的项目,项目的名称为cloud-header-demo,接着在该项目底下创建我们的注册中心的module。
    在这里插入图片描述
    接着我们引入我们的eureka的依赖,pom.xml的代码如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.6.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.cloud.header</groupId>
        <artifactId>eureka-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>eureka-demo</name>
        <description>注册中心例子</description>
    
        <properties>
            <java.version>1.8</java.version>
            <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>${spring-cloud.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    

    接着我们修改我们的配置文件application.yml修改完成以后代码如下:

    spring:
      application:
        # 工程名字
        name: eureka-demo
    
    server:
      port: 2100
    
    eureka:
      client:
        #缓存清单的更新时间,默认是30秒
        registry-fetch-interval-seconds: 30
        service-url:
          # 注册中心的地址
          defaultZone: http://127.0.0.1:2100/eureka/
      server:
        # 默认情况下,如果Eureka Server在一定时间内没有接收到某个微服务实例的心跳,Eureka Server将会注销该实例(默认90秒)。
        # 但是当网络分区故障发生时,微服务与Eureka Server之间无法正常通信,
        # 以上行为可能变得非常危险了——因为微服务本身其实是健康的,此时本不应该注销这个微服务。
        # Eureka通过“自我保护模式”来解决这个问题——当Eureka Server节点在短时间内丢失过多客户端时(可能发生了网络分区故障),
        # 那么这个节点就会进入自我保护模式。一旦进入该模式,Eureka Server就会保护服务注册表中的信息,不再删除服务注册表中的数据(也就是不会注销任何微服务)。
        # 当网络故障恢复后,该Eureka Server节点会自动退出自我保护模式。
        enable-self-preservation: true
        #节点间的读数据连接超时时间单位毫秒
        peer-node-read-timeout-ms: 1000
    
    

    最后在我们的启动类上添加以下的注解

    @SpringBootApplication
    @EnableEurekaServer
    public class EurekaDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(EurekaDemoApplication.class, args);
        }
    
    }
    

    创建生产者

    接着我们在cloud-header-demo底下创建我们的produce-demo的生产者项目。
    在这里插入图片描述
    接着我们引入我们的eureka的依赖,pom.xml的代码如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.6.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.cloud.header</groupId>
        <artifactId>produce-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>produce-demo</name>
        <description>生产者的demo例子</description>
    
        <properties>
            <java.version>1.8</java.version>
            <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>${spring-cloud.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
    

    接着我们修改我们的配置文件application.yml修改完成以后代码如下:

    server:
      port: 11100
    
    
    spring:
      servlet:
        multipart:
          max-file-size: 100MB
          max-request-size: 500MB
      application:
        name: produce-demo
    
    
    eureka:
      client:
        service-url:
          defaultZone: http://127.0.0.1:2100/eureka/
      instance:
        instance-id: ${spring.cloud.client.ip-address}:${server.port}
    
    

    最后我们编写一个最简单的controller方法来获取我们消费者传送过来的自定义的header

    @RestController
    public class HeaderController {
    
        @GetMapping("getConsumerHeader")
        public String getConsumerHeader(){
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String consumerHeader = request.getHeader("consumerHeader");
            if(consumerHeader!=null && !"".equals(consumerHeader)){
                System.out.println("----" + URLDecoder.decode(consumerHeader,"GBK"));
            }else{
                System.out.println("----" +  consumerHeader);
            }
            return "success";
        }
    
    }
    

    接着我们启动我们的注册中心和生产者,我们使用访问:http://127.0.0.1:11100/getConsumerHeader 这时候我们会看到我们的请求头里面并没有我们自定义的头部信息:
    在这里插入图片描述

    创建消费者

    此处就是我们本章的核心部分了,我们该如何实现在调用其他生产者的时候把我们自定义的header传给下一个生产者呢,首先在cloud-header-demo底下创建我们的consumer-demo的消费者项目。
    在这里插入图片描述
    接着我们引入我们的eureka和feign的依赖,pom.xml的代码如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.6.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.cloud.header</groupId>
        <artifactId>consumer-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>consumer-demo</name>
        <description>这是一个消费者的例子</description>
    
        <properties>
            <java.version>1.8</java.version>
            <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>${spring-cloud.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    </project>
    

    接着我们修改我们的配置文件application.yml修改完成以后代码如下:

    server:
      port: 12100
    
    
    spring:
      servlet:
        multipart:
          # 单个文件上传的最大值
          max-file-size: 100MB
          # 多个文件上传的总的最大值
          max-request-size: 500MB
      cloud:
        loadbalancer:
          retry:
            # 该参数用来开启重试机制,它默认是关闭的。
            enabled: true
      application:
        name: user-demo
    
    
    eureka:
      client:
        service-url:
          # 注册中心地址
          defaultZone: http://127.0.0.1:2100/eureka/
      instance:
        # 配置在eureka上status栏显示的信息
        instance-id: ${spring.cloud.client.ip-address}:${server.port}
    
    feign:
      hystrix:
        # 关闭hystrix默认就是关闭,若是设置为true的话一定要记得配置超时的时间,要不到时候可能会导致超时失败,因此最好将此处的熔断机制给去除
        enabled: false
      compression:
        # 开启GZIP的压缩功能以减少HTTP通信的消耗。
        request:
          enabled: true
          # 以下的请求的类型且请求数据的大小超过2048的将为会压缩传输。
          min-request-size: 2048
          mime-types: text/xml,application/xml,application/json
        response:
          enabled: true
    
    ribbon:
      # #请求连接的超时时间。
      ConnectTimeout: 6000
      # 请求处理的超时时间,该超时时间的影响层级大于全局的超时时间,设置了该时间那么,如果调用生产端的时候超过1秒那么就直接调用重试规则,因此若重试次数和切换次数都是为1那么,响应的时间不超过4秒
      ReadTimeout: 60000
      # 对所有操作请求都进行重试。
      OkToRetryOnAllOperations: true
      # 以下重试实现响应EUREKA-PRODUCER的最大次数是 :(1 + MaxAutoRetries)* (1 + MaxAutoRetriesNextServer)
      # 假设 MaxAutoRetries = 2 ,MaxAutoRetriesNextServer = 4 ,那么最大的重试次数为15次
      # 切换实例的重试次数。
      MaxAutoRetriesNextServer: 1
      # 对当前实例的重试次数。
      MaxAutoRetries: 1
    

    接着在我们的启动类上添加以下的注解

    @SpringBootApplication
    @EnableFeignClients
    @EnableDiscoveryClient
    public class ConsumerDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(ConsumerDemoApplication.class, args);
        }
    
    }
    

    最后我们开始编写我们的相关的实现,首先我们创建一个config包,在该包底下创建一个FeignConfiguration的配置代码如下:

    package com.cloud.header.consumer.demo.config;
    
    import feign.Logger;
    import feign.RequestInterceptor;
    import feign.RequestTemplate;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import javax.servlet.http.HttpServletRequest;
    import java.util.Enumeration;
    
    /**
     * 类描述:feign在调用生产者的时候回把header传过去,若不配置则不传送request头
     * @author linzf
     */
    @Configuration
    public class FeignConfiguration {
    
        @Bean
        Logger.Level feignLoggerLevel() {
            // • NONE: 不记录任何信息。
            // • BASIC: 仅记录请求方法、URL以及响应状态码和执行时间。
            // • HEADERS: 除了记录BASIC级别的信息之外, 还会记录请求和响应的头信息。
            // • FULL: 记录所有请求与响应的明细, 包括头信息、 请求体、 元数据等。
            return Logger.Level.FULL;
        }
    
        @Bean
        public RequestInterceptor requestInterceptor() {
            return new RequestInterceptor() {
                @Override
                public void apply(RequestTemplate template) {
                    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                            .getRequestAttributes();
                    HttpServletRequest request = attributes.getRequest();
                    Enumeration<String> headerNames = request.getHeaderNames();
                    if (headerNames != null) {
                        while (headerNames.hasMoreElements()) {
                            String name = headerNames.nextElement();
                            String values = request.getHeader(name);
                            template.header(name, values);
                        }
                    }
                }
            };
        }
    }
    

    接着创建一个feign包,在底下创建我们的feign的调用HeaderFeign,代码如下:

    package com.cloud.header.consumer.demo.feign;
    
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.GetMapping;
    
    /**
     * @author linzf
     * @since 2019/7/23
     * 类描述:
     */
    @FeignClient(value="PRODUCE-DEMO")
    public interface HeaderFeign {
    
        /**
         * 功能描述:实现调用生产者的方法
         * @return 返回调用结果
         */
        @GetMapping("getConsumerHeader")
        String getConsumerHeader();
    
    }
    
    

    接着创建一个controller包,在底下创建HeaderController,代码实现如下:

    package com.cloud.header.consumer.demo.controller;
    
    import com.cloud.header.consumer.demo.feign.HeaderFeign;
    import org.apache.tomcat.util.http.MimeHeaders;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import javax.servlet.http.HttpServletRequest;
    import java.lang.reflect.Field;
    
    /**
     * @author linzf
     * @since 2019/7/23
     * 类描述:
     */
    @RestController
    public class HeaderController {
    
        @Autowired
        private HeaderFeign headerFeign;
    
        @GetMapping("getConsumerHeader")
        public String getConsumerHeader(){
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            // 中文在请求头中会变为乱码,因此要进行转化
            reflectSetHeader(request,"consumerHeader", URLEncoder.encode("我是从消费者传过来的请求头", "GBK"));
            return headerFeign.getConsumerHeader();
        }
    
        /**
         * 功能描述:实现往请求里加入我们的header
         * @param request request对象
         * @param key header的key
         * @param value header的值
         */
        private void reflectSetHeader(HttpServletRequest request, String key, String value){
            Class<? extends HttpServletRequest> requestClass = request.getClass();
            try {
                Field request1 = requestClass.getDeclaredField("request");
                request1.setAccessible(true);
                Object o = request1.get(request);
                Field coyoteRequest = o.getClass().getDeclaredField("coyoteRequest");
                coyoteRequest.setAccessible(true);
                Object o1 = coyoteRequest.get(o);
                Field headers = o1.getClass().getDeclaredField("headers");
                headers.setAccessible(true);
                MimeHeaders o2 = (MimeHeaders)headers.get(o1);
                o2.removeHeader(key);
                o2.addValue(key).setString(value);
            } catch (Exception e) {
    
            }
        }
    }
    

    验证结果

    最后我们将我们的注册中心,消费者和生产者全部启动起来,然后我们在浏览器访问以下的网址:http://127.0.0.1:12100/getConsumerHeader
    在这里插入图片描述
    这时候我们的生产者就获取了消费者传过来的请求头的信息了,到此为止我们就完成了我们的微服务之间自定义请求头的传送了,到此为止的代码,大家可以直接去github上下载运行,github上的地址:https://github.com/lazyboyl/cloud-header-demo

    展开全文
  • 这问题简直像恶魔一样特喵的~喵喵喵 ? 参考资料: ...跨域踩坑经验总结(内涵:跨域知识科普) - 凝雨 - Yun ... try_files $uri $uri / /index.php? $query_string ; } # 下方为其它配置... }

    这问题简直像恶魔一样特喵的~喵喵喵?


    参考资料:

    前后端分离项目

    假设现在前端地址为:b.example.com;接口地址为 api.example.com,且 Nginx 对应配置已搞妥。

    编辑 api.example.com 地址的配置文件:

    server {
        # 上方是该 Server 相关的端口、root 路径、index 一类设置
        # 这儿设置默认请求允许跨域(建议发布环境指定域名而不是“星”号,如 http://b.example.com)
        add_header Access-Control-Allow-Origin '*';
    
        location / {
            # 强制 HTTPS 跳转,不需要直接移除
            #if ($scheme = http) {
            #    return 301 https://$host$request_uri;
            #}
    
            # 根据 SF 里面大佬的解释,如果请求不是 GET 或者特定 POST(指定 Content-Type)时,
            # 浏览器会以 OPTIONS 方式发送一个预请求,
            # 所以在预请求的响应阶段,我们得允许跨域的相关操作
            if ($request_method = 'OPTIONS') {
                # 【必须】,同上说明,建议在发布环境用域名而不是“星”号
                add_header Access-Control-Allow-Origin '*';
                # Allow-Headers 指定允许的自定义请求头,如用户 Token
                add_header Access-Control-Allow-Headers 'App-Token';
                # 经过我的实验这个可以不加(有需要另说)
                # 一般来说在 POST 请求时因为 Content-Type 的原因在本次 OPTIONS 预请求后,
                # 会再发送的 POST 请求,而 POST 请求是可以正常接收的
                add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, PATCH, OPTIONS';
                # 请求是否携带 Cookie,无需要可忽略。有说该设置为 true 时 Allow-Origin 不可为 '*'
                add_header Access-Control-Allow-Credentials true;
                # 这个响应 Content-Type 也是根据需要设置(一般情况可以不用设置)
                add_header Content-Type 'application/json; charset=utf-8';
                # 如下 Content-Length 可忽略,返回状态码根据个人习惯可设置为 200
                add_header Content-Length 0;
                return 204;
            }
    
            # 因使用 Laravel/Lumen 框架,所以有这句,请删掉不用在意...
            try_files $uri $uri/ /index.php?$query_string;
        }
    
        # 下方为其它配置...
    }
    	
    
    展开全文
  • HttpServletRequest添加header

    万次阅读 2019-05-10 15:51:09
    try { HttpServletRequestImpl httpRequest = (HttpServletRequestImpl) request; HttpServerExchange exchange = httpRequest.getExchange(); HeaderMap headerMap = exchange.getRequestHeaders(); for (Map....

    在java web开发中,我们有时候会遇到需要修改request中请求值的问题,虽然这个不是特别常见。初看这是一个简单的问题,因为我们能通过HttpServletRequest对象拿到我们需要的所有关于当前这个请求的所有信息,想当然的也就可以修改所以这些信息。可实际情况是HttpServletReques中很多的属性只有getter方法,而没有setter方法,也就是说我们不可以修改他们。
    记得第一次遇到这种问题还是初学编程的时候,最近又遇到这个问题,就记录一下。最近遇到的是在spring mvc中,使用@RequestBody注解把requestBody中的json映射到java的object。我们知道对于spring mvc来说,这样使用的时候需要在请求的header里面表明conten-type为application/json。如果完全是自己开发的系统,没有问题加上就是,但是当和第三方合作的时候,请求的发起方式就不是我们能控制住的了。现在的问题是如果使用spring mvc的这种开发模式,必须要在请求的header中设置content-type为application/json,但是第三方又不方便设置。所以只能在所有针对第三方的API中进行特殊处理。
    sping mvc是基于servlet的,我们只要在请求进入servlet之前的拦截器设置header中content-type为application/json就ok了.

       /**
     * 统一token校验
     * @author luca
     */
    public class GlobalInterceptorHandler extends HandlerInterceptorAdapter {
        private final Logger logger = LoggerFactory.getLogger(GlobalInterceptorHandler.class);
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            //如果是options请求直接放过
            if(request.getMethod().matches(HttpMethod.OPTIONS.name())){
                return true;
            }
            if(!(handler instanceof HandlerMethod)) {
                return true;
            }
            logger.info("request请求地址path[{}] uri[{}]", request.getServletPath(),request.getRequestURI());
            Map<String,String> headerses = new HashMap<>();
            headerses.put("content-type","application/json");
            modifyHeaders(request,headerses);
            return true;
        }
    
        /**
         * 修改请求头信息
         * @param headerses
         * @param request
         */
        private void modifyHeaders(HttpServletRequest request,Map<String, String> headerses) {
            if (headerses == null || headerses.isEmpty()) {
                return;
            }
            try {
                HttpServletRequestImpl httpRequest = (HttpServletRequestImpl) request;
                HttpServerExchange exchange = httpRequest.getExchange();
                HeaderMap headerMap = exchange.getRequestHeaders();
                for (Map.Entry<String, String> entry : headerses.entrySet()) {
                    headerMap.add(new HttpString(entry.getKey()), entry.getValue());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                               ModelAndView modelAndView) throws Exception {
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception {}
    }
    
    展开全文
  • header fields 详解

    千次阅读 2018-08-28 16:52:23
    List of HTTP header fields 翻译 标准要求字段 字段名 说明 例子 状态 A-IM 可接受实例操作的请求 A-IM: feed 永久的 Accept 对于响应来说是(/是)可接受的媒体类型。看到内容协商。 Accept: ...

    参考

    List of HTTP header fields

    翻译

    标准要求字段

    字段名说明例子状态
    A-IM可接受实例操作的请求A-IM: feed永久的
    Accept对于响应来说是(/是)可接受的媒体类型。看到内容协商。Accept: text/html永久的
    Accept-Charset可接受的字符集。Accept-Charset: utf-8永久的
    Accept-Datetime可接受的版本。Accept-Datetime: Thu, 31 May 2007 20:35:00 GMT临时的
    Accept-Encoding可接受的编码列表。看到HTTP压缩。Accept-Encoding: gzip, deflate永久的
    Accept-Language可接受的人类语言列表。看到内容协商。Accept-Language: en-US永久的
    Access-Control-Request-Method
    Access-Control-Request-Headers[8]
    启动与Origin共享跨源资源的请求(如下所示)。Access-Control-Request-Method: GET永久的
    AuthorizationHTTP身份验证的身份验证凭据。Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==永久的
    Cache-Control用于指定沿着请求-响应链的所有缓存机制必须遵守的指令。Cache-Control: no-cache永久的
    Connection当前连接的控制选项和逐跳请求字段的列表。Connection: keep-alive
    Connection: Upgrade
    永久的
    Content-Length请求体的长度(8位字节)。Content-Length: 348永久的
    Content-MD5请求体内容的一种base64编码的二进制MD5的和。Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==废弃的
    Content-Type请求主体的媒体类型(与POST和PUT请求一起使用)。Content-Type: application/x-www-form-urlencoded永久的
    Cookie先前服务器通过Set-Cookie发送的HTTP cookie(如下所示)。Cookie: $Version=1; Skin=new;永久的
    Date消息发出的日期和时间(以RFC 7231日期/时间格式定义的“HTTP-date”格式)。Date: Tue, 15 Nov 1994 08:12:31 GMT永久的
    Expect指示客户端需要特定的服务器行为。Expect: 100-continue永久的
    Forwarded通过HTTP代理.公开连接到web服务器的客户机的原始信息Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43 Forwarded: for=192.0.2.43, for=198.51.100.17永久的
    From发出请求的用户的电子邮件地址。From: user@example.com永久的
    Host主机Host: en.wikipedia.org:8080
    Host: en.wikipedia.org
    永久的
    If-Match只有当客户机提供的实体与服务器上的相同实体匹配时,才执行该操作。这主要是针对像PUT to这样的方法,如果资源在用户上次更新后没有被修改,则只更新它。If-Match: “737060cd8c284d8af7ad3082f209582d”永久的
    If-Modified-Since如果内容不变,则允许返回未修改的304。If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT永久的
    If-None-Match如果内容不变,允许返回不修改的304,请参阅HTTP ETag。If-None-Match: “737060cd8c284d8af7ad3082f209582d”永久的
    If-Range如果实体不变,请将我遗漏的部分发送给我;否则,将整个新实体发送给我。If-Range: “737060cd8c284d8af7ad3082f209582d”永久的
    If-Unmodified-SinceOnly send the response if the entity has not been modified since a specific time.If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT永久的
    Max-ForwardsLimit the number of times the message can be forwarded through proxies or gateways.Max-Forwards: 10永久的
    Origin[8]Initiates a request for cross-origin resource sharing (asks server for Access-Control-* response fields).Origin: http://www.example-social-network.com永久的
    PragmaImplementation-specific fields that may have various effects anywhere along the request-response chain.Pragma: no-cache永久的
    Proxy-AuthorizationAuthorization credentials for connecting to a proxy.Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==永久的
    RangeRequest only part of an entity. Bytes are numbered from 0. See Byte serving.Range: bytes=500-999永久的
    Referer [sic]This is the address of the previous web page from which a link to the currently requested page was followed. (The word “referrer” has been misspelled in the RFC as well as in most implementations to the point that it has become standard usage and is considered correct terminology)Referer: http://en.wikipedia.org/wiki/Main_Page永久的
    TEThe transfer encodings the user agent is willing to accept: the same values as for the response header field Transfer-Encoding can be used, plus the “trailers” value (related to the “chunked” transfer method) to notify the server it expects to receive additional fields in the trailer after the last, zero-sized, chunk.Only trailers is supported in HTTP/2.TE: trailers, deflate永久的
    UpgradeAsk the server to upgrade to another protocol. Must not be used in HTTP/2.Upgrade: h2c, HTTPS/1.3, IRC/6.9, RTA/x11, websocket永久的
    User-AgentThe user agent string of the user agent.User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0永久的
    ViaInforms the server of proxies through which the request was sent.Via: 1.0 fred, 1.1 example.com (Apache/1.1)永久的
    WarningA general warning about possible problems with the entity body.Warning: 199 Miscellaneous warning永久的

    常见的非标准要求字段

    Field nameDescriptionExample
    Upgrade-Insecure-RequestsTells a server which (presumably in the middle of a HTTP -> HTTPS migration) hosts mixed content that the client would prefer redirection to HTTPS and can handle Content-Security-Policy: upgrade-insecure-requests Must not be used with HTTP/2Upgrade-Insecure-Requests: 1
    X-Requested-WithMainly used to identify Ajax requests. Most JavaScript frameworks send this field with value of XMLHttpRequestX-Requested-With: XMLHttpRequest
    DNTRequests a web application to disable their tracking of a user. This is Mozilla’s version of the X-Do-Not-Track header field (since Firefox 4.0 Beta 11). Safari and IE9 also have support for this field. On March 7, 2011, a draft proposal was submitted to IETF.[18] The W3C Tracking Protection Working Group is producing a specification.DNT: 1 (Do Not Track Enabled)
    DNT: 0 (Do Not Track Disabled)
    X-Forwarded-ForA de facto standard for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or load balancer. Superseded by Forwarded header.X-Forwarded-For: client1, proxy1, proxy2
    X-Forwarded-HostA de facto standard for identifying the original host requested by the client in the Host HTTP request header, since the host name and/or port of the reverse proxy (load balancer) may differ from the origin server handling the request. Superseded by Forwarded header.X-Forwarded-Host: en.wikipedia.org:8080
    X-Forwarded-Host: en.wikipedia.org
    X-Forwarded-ProtoA de facto standard for identifying the originating protocol of an HTTP request, since a reverse proxy (or a load balancer) may communicate with a web server using HTTP even if the request to the reverse proxy is HTTPS. An alternative form of the header (X-ProxyUser-Ip) is used by Google clients talking to Google servers. Superseded by Forwarded header.X-Forwarded-Proto: https
    Front-End-HttpsNon-standard header field used by Microsoft applications and load-balancersFront-End-Https: on
    X-Http-Method-OverrideRequests a web application to override the method specified in the request (typically POST) with the method given in the header field (typically PUT or DELETE). This can be used when a user agent or firewall prevents PUT or DELETE methods from being sent directly (note that this is either a bug in the software component, which ought to be fixed, or an intentional configuration, in which case bypassing it may be the wrong thing to do).X-HTTP-Method-Override: DELETE
    X-ATT-DeviceIdAllows easier parsing of the MakeModel/Firmware that is usually found in the User-Agent String of AT&T DevicesX-Att-Deviceid: GT-P7320/P7320XXLPG
    X-Wap-ProfileLinks to an XML file on the Internet with a full description and details about the device currently connecting. In the example to the right is an XML file for an AT&T Samsung Galaxy S2.x-wap-profile: http://wap.samsungmobile.com/uaprof/SGH-I777.xml
    Proxy-ConnectionImplemented as a misunderstanding of the HTTP specifications. Common because of mistakes in implementations of early HTTP versions. Has exactly the same functionality as standard Connection field.Must not be used with HTTP/2.[10]Proxy-Connection: keep-alive
    X-UIDHServer-side deep packet insertion of a unique ID identifying customers of Verizon Wireless; also known as “perma-cookie” or “supercookie”X-UIDH: …
    X-Csrf-TokenUsed to prevent cross-site request forgery. Alternative header names are: X-CSRFToken[32] and X-XSRF-TOKEN[33]X-Csrf-Token: i8XNjC4b8KVok4uw5RftR38Wgp2BFwql
    X-Request-ID
    X-Correlation-ID
    Correlates HTTP requests between a client and server.X-Request-ID: f058ebd6-02f7-4d3f-942e-904344e8cde5
    Save-DataThe Save-Data client hint request header available in Chrome, Opera, and Yandex browsers lets developers deliver lighter, faster applications to users who opt-in to data saving mode in their browser.Save-Data: on

    标准回复字段

    Field nameDescriptionExampleStatus
    Access-Control-Allow-Origin
    Access-Control-Allow-Credentials
    Access-Control-Expose-Headers
    Access-Control-Max-Age
    Access-Control-Allow-Methods
    Access-Control-Allow-Headers
    Specifying which web sites can participate in cross-origin resource sharingAccess-Control-Allow-Origin: *Permanent: standard
    Accept-PatchSpecifies which patch document formats this server supportsAccept-Patch: text/example;charset=utf-8Permanent
    Accept-RangesWhat partial content range types this server supports via byte servingAccept-Ranges: bytesPermanent
    AgeThe age the object has been in a proxy cache in secondsAge: 12Permanent
    AllowValid methods for a specified resource. To be used for a 405 Method not allowedAllow: GET, HEADPermanent
    Alt-SvcA server uses “Alt-Svc” header (meaning Alternative Services) to indicate that its resources can also be accessed at a different network location (host or port) or using a different protocol
    When using HTTP/2, servers should instead send an ALTSVC frame. [40]
    Alt-Svc: http/1.1=”http2.example.com:8001”; ma=7200Permanent
    Cache-ControlTells all caching mechanisms from server to client whether they may cache this object. It is measured in secondsCache-Control: max-age=3600Permanent
    ConnectionControl options for the current connection and list of hop-by-hop response fields.[9]
    Must not be used with HTTP/2.[10]
    Connection: closePermanent
    Content-Disposition[41]An opportunity to raise a “File Download” dialogue box for a known MIME type with binary format or suggest a filename for dynamic content. Quotes are necessary with special characters.Content-Disposition: attachment; filename=”fname.ext”Permanent
    Content-EncodingThe type of encoding used on the data. See HTTP compression.Content-Encoding: gzipPermanent
    Content-LanguageThe natural language or languages of the intended audience for the enclosed content[42]Content-Language: daPermanent
    Content-LengthThe length of the response body in octets (8-bit bytes)Content-Length: 348Permanent
    Content-LocationAn alternate location for the returned dataContent-Location: /index.htmPermanent
    Content-MD5A Base64-encoded binary MD5 sum of the content of the responseContent-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==Obsolete[11]
    Content-RangeWhere in a full body message this partial message belongsContent-Range: bytes 21010-47021/47022Permanent
    Content-TypeThe MIME type of this contentContent-Type: text/html; charset=utf-8Permanent
    DateThe date and time that the message was sent (in “HTTP-date” format as defined by RFC 7231) [43]Date: Tue, 15 Nov 1994 08:12:31 GMTPermanent
    Delta-BaseSpecifies the delta-encoding entity tag of the response[7].Delta-Base: “abc”Permanent
    ETagAn identifier for a specific version of a resource, often a message digestETag: “737060cd8c284d8af7ad3082f209582d”Permanent
    ExpiresGives the date/time after which the response is considered stale (in “HTTP-date” format as defined by RFC 7231)Expires: Thu, 01 Dec 1994 16:00:00 GMTPermanent: standard
    IMInstance-manipulations applied to the response[7].IM: feedPermanent
    Last-ModifiedThe last modified date for the requested object (in “HTTP-date” format as defined by RFC 7231)Last-Modified: Tue, 15 Nov 1994 12:45:26 GMTPermanent
    LinkUsed to express a typed relationship with another resource, where the relation type is defined by RFC 5988Link: ; rel=”alternate”[44]Permanent
    LocationUsed in redirection, or when a new resource has been created.
    Example 1: Location: http://www.w3.org/pub/WWW/People.html
    Example 2: Location: /pub/WWW/People.html
    Permanent
    P3PThis field is supposed to set P3P policy, in the form of P3P:CP=”your_compact_policy”. However, P3P did not take off,[45] most browsers have never fully implemented it, a lot of websites set this field with fake policy text, that was enough to fool browsers the existence of P3P policy and grant permissions for third party cookies.P3P: CP=”This is not a P3P policy! See https://en.wikipedia.org/wiki/Special:CentralAutoLogin/P3P for more info.”Permanent
    PragmaImplementation-specific fields that may have various effects anywhere along the request-response chain.Pragma: no-cachePermanent
    Proxy-AuthenticateRequest authentication to access the proxy.Proxy-Authenticate: BasicPermanent
    Public-Key-Pins[46]HTTP Public Key Pinning, announces hash of website’s authentic TLS certificatePublic-Key-Pins: max-age=2592000; pin-sha256=”E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=”;Permanent
    Retry-AfterIf an entity is temporarily unavailable, this instructs the client to try again later. Value could be a specified period of time (in seconds) or a HTTP-date.[47]
    Example 1: Retry-After: 120
    Example 2: Retry-After: Fri, 07 Nov 2014 23:59:59 GMT
    Permanent
    ServerA name for the serverServer: Apache/2.4.1 (Unix)Permanent
    Set-CookieAn HTTP cookieSet-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1Permanent: standard
    Strict-Transport-SecurityA HSTS Policy informing the HTTP client how long to cache the HTTPS only policy and whether this applies to subdomains.Strict-Transport-Security: max-age=16070400; includeSubDomainsPermanent: standard
    TrailerThe Trailer general field value indicates that the given set of header fields is present in the trailer of a message encoded with chunked transfer coding.Trailer: Max-ForwardsPermanent
    Transfer-EncodingThe form of encoding used to safely transfer the entity to the user. Currently defined methods are: chunked, compress, deflate, gzip, identity.
    Must not be used with HTTP/2.[10]
    Transfer-Encoding: chunkedPermanent
    TkTracking Status header, value suggested to be sent in response to a DNT(do-not-track), possible values: ` “!” — nder construction
    “?” — dynamic
    “G” — gateway to multiple parties
    “N” — not tracking
    “T” — tracking
    “C” — tracking with consent
    “P” — tracking only if consented
    “D” — disregarding DNT
    “U” — updated
    Tk: ?Permanent
    UpgradeAsk the client to upgrade to another protocol.
    Must not be used in HTTP/2[10]
    Upgrade: h2c, HTTPS/1.3, IRC/6.9, RTA/x11, websocketPermanent
    VaryTells downstream proxies how to match future request headers to decide whether the cached response can be used rather than requesting a fresh one from the origin server.
    Example 1: Vary: *
    Example 2: Vary: Accept-Language
    Permanent
    ViaInforms the client of proxies through which the response was sent.Via: 1.0 fred, 1.1 example.com (Apache/1.1)Permanent
    WarningA general warning about possible problems with the entity body.Warning: 199 Miscellaneous warningPermanent
    WWW-AuthenticateIndicates the authentication scheme that should be used to access the requested entity.WWW-Authenticate: BasicPermanent
    X-Frame-Options[48]Clickjacking protection: deny - no rendering within a frame, sameorigin - no rendering if origin mismatch, allow-from - allow from specified location, allowall - non-standard, allow from any locationX-Frame-Options: denyObsolete[49]

    常见的非标准响应领域

    Field nameDescriptionExample
    Content-Security-Policy,
    X-Content-Security-Policy,
    X-WebKit-CSP[50]Content Security Policy definition.X-WebKit-CSP: default-src ‘self’
    RefreshUsed in redirection, or when a new resource has been created. This refresh redirects after 5 seconds. Header extension introduced by Netscape and supported by most web browsers.Refresh: 5; url=http://www.w3.org/pub/WWW/People.html
    StatusCGI header field specifying the status of the HTTP response. Normal HTTP responses use a separate “Status-Line” instead, defined by RFC 7230.[51]Status: 200 OK
    Timing-Allow-OriginThe Timing-Allow-Origin response header specifies origins that are allowed to see values of attributes retrieved via features of the Resource Timing API, which would otherwise be reported as zero due to cross-origin restrictions.[52]Timing-Allow-Origin: *
    Timing-Allow-Origin: [, ]*
    X-Content-Duration[53]Provide the duration of the audio or video in seconds; only supported by Gecko browsersX-Content-Duration: 42.666
    X-Content-Type-Options[54]The only defined value, “nosniff”, prevents Internet Explorer from MIME-sniffing a response away from the declared content-type. This also applies to Google Chrome, when downloading extensions.[55]X-Content-Type-Options: nosniff[56]
    X-Powered-By[57]Specifies the technology (e.g. ASP.NET, PHP, JBoss) supporting the web application (version details are often in X-Runtime, X-Version, or X-AspNet-Version)X-Powered-By: PHP/5.4.0
    X-Request-ID,
    X-Correlation-ID[34]Correlates HTTP requests between a client and server.X-Request-ID: f058ebd6-02f7-4d3f-942e-904344e8cde5
    X-UA-Compatible[58]Recommends the preferred rendering engine (often a backward-compatibility mode) to use to display the content. Also used to activate Chrome Frame in Internet Explorer.X-UA-Compatible: IE=EmulateIE7
    X-UA-Compatible: IE=edge
    X-UA-Compatible: Chrome=1
    X-XSS-Protection[59]Cross-site scripting (XSS) filterX-XSS-Protection: 1; mode=block
    展开全文
  • C++中try/catch/throw的使用

    万次阅读 多人点赞 2017-03-25 19:12:46
    C++异常处理涉及到三个关键字:try、catch、throw。 在C++语言中,异常处理包括: (1)、throw表达式:异常检测部分使用throw表达式来表示它遇到了无法处理的问题,throw引发了异常。throw表达...
  • jwt

    千次阅读 2019-08-17 22:19:01
    它验证的方法其实很简单,只要把header做base64url解码,就能知道JWT用的什么算法做的签名,然后用这个算法,再次用同样的逻辑对header和payload做一次签名, 并比较这个签名是否与JWT本身包含的第三个部分的串...
  • try-except模块

    2020-12-22 03:01:13
    try-except模块 如果try代码块中的代码导致了错误,python将查找这样的except代码块,并运行其中的代码,即指定的错误与引发的错误相同。 例程: ... header_row = next(reader) dates,highs,lows=
  • Please install the Linux kernel “header” files matching the current kernel 当我启动minilkube时遇到如下错误消息: ################################################################################ ...
  • fresco添加http header

    千次阅读 2016-01-25 16:14:10
    今天使用fresco时,项目中在加载图片时添加了防盗链,需要在获取图片时添加header信息,研究了下fresco如何添加header,解决方案如下: 1、新建一个类ElnImageDownloaderFetcher,继承...
  • Python读取Excel文件

    万次阅读 多人点赞 2018-03-06 14:22:16
    Python读取excel文件内容十分方便,为以下几个步骤: (1)安装python官方Excel库–&gt;xlrd (2)获取Excel文件位置并读取 (3)读取sheet (4)读取指定rows和cols内容 ... try: data = xlrd....
  • BaseRecyclerViewAdapterHelper源码解读(二) 添加header和footer原项目地址: https://github.com/CymChad/BaseRecyclerViewAdapterHelper,首先感谢开源,感谢无私奉献的人们.... //header footer private Lin
  • Nginx的try_files指令详解

    千次阅读 2020-11-26 14:52:11
    在0.7以后的版本中加入了一个try_files指令,配合命名location,可以部分替代原本常用的rewrite配置方式,提高解析效率。 查看nginx手册 try_files 语法: try_files file ... uri 或 try_files file ... = code ...
  • http请求头header、请求体body、请求行介绍

    万次阅读 多人点赞 2019-06-09 09:47:54
    往请求头header里设置参数和参数value,可以使用HttpClient访问rest接口,往请求头里添加token验证信息 CloseableHttpClient client = HttpClients.createDefault();  HttpGet get = new HttpGet(...
  • httpServletRequest添加header

    千次阅读 2020-05-16 10:17:38
    反射机制设置header private void reflectSetHeader(HttpServletRequest request, String key, String value){ Class<? extends HttpServletRequest> requestClass = request.getClass(); try { Field ...
  • 【Webservice】客户端调用设置header

    千次阅读 热门讨论 2018-03-27 19:40:33
    但是这次调用erp系统的接口需要设置header,本来才soapUI测试没什么问题,但是用代码实现就出了问题 因为它不是写在envelope里面,而是直接在请求中的header中,尝试了很多方法,最终实现了,不过其他的尝试或许...
  • 修改Header方法

    千次阅读 2019-05-09 19:04:54
    * 修改header信息,key-value键值对儿加入到header中,如果存在,替换 * @param request * @param key * @param value */ public static void reflectRequestParam(HttpServletRequest request, String key, ...
  • Spring Cloud Feign 透传Header信息

    千次阅读 2019-02-28 10:28:43
    Spring Cloud 微服务下,通过Feign相互调用时,Feign是不会带上当前请求的cookie信息和header信息,而我们一般都会在cookie或者header带着一些重要的信息,如cookieid,token等。那么我们怎么将这些信息传递到其他的...
  • response里的setHeader用法

    千次阅读 2017-09-25 14:23:53
    response.setHeader()的用法 1. HTTP消息头 (1)通用信息头 即能用于请求消息中,也能用于响应信息中,但与被传输的实体内容没有关系的信息头,如Data,Pragma 主要: Cache-Control , Connection , ...
  • 问题场景 微服务A通过feign调用微服务B ...找到可以给feign调用添加header的切入点,在这里获取主线程ThreadLocal中的数据并添加到header中 找到Hystrix开启新的子线程的切入点,在线程执行run方法的先后分别做数据
  • Feign动态设置Header

    千次阅读 2019-12-25 14:21:54
    try { Object userInfo = authorityConfig.userInfoFeignClient(token).getUserInfoByToken(token); return userInfo; } catch (Exception e) { log.info("获取用户信息异常", e); return null; } }
  • webview添加header,cookie 和性能优化

    千次阅读 2018-08-14 12:22:39
    webview添加header webview添加cookie WebView的启动优化 webview的缓存,节省内存减少流量 参考文档: webview优缺点   app中使用h5可以使内容更新更加灵活。周期更短。并且代码量也少,是apk的体积变小...
  • Python网络爬虫爬淘宝无法爬取问题的解决方法

    千次阅读 热门讨论 2019-09-14 21:02:57
    r=requests.get(url,headers=header,timeout=30) r.raise_for_status() r.encoding=r.apparent_encoding # print(r.text) return r.text except: return "" def parsePage(ilt,html): #解析获得的页面 try:...
  • 上一篇文章阐述了通用的flume+kafka+storm模式,若是有如下需要:在传输数据的同时,携带header头文件信息,比如在传输文件的同时,在flume Event的header中携带文件的元数据,该怎么处理呢。 上一篇文章连接:...
  • setHeader方法的使用

    万次阅读 2018-05-24 15:28:30
    response.setHeader()下载中文文件名乱码1. HTTP消息头(1)通用信息头即能用于请求消息中,也能用于响应信息中,但与被传输的实体内容没有关系的信息头,如Data,Pragma主要: Cache-Control , Connection , Data , ...
  • try { return messageSource.getMessage(msgCode, null, LocaleContextHolder.getLocale()); } catch (Exception e) { return msgCode; } } } 6、测试 Http请求头,添加Accept-Language节点即可
  • Header(headerName, defaultValue); } /// /// 获取Header值 /// /// 类型 /// <param name="headerName"> Header名称 /// 默认值 /// public static T Header( ...
  • 目录一、Header传值 1.客户端实现拦截器 2.客户端注入拦截器 3.服务端实现拦截器 4.服务端注入拦截器 5.输出信息 二、错误信息处理 ...
  • HTTP GET添加Header请求头

    万次阅读 2020-02-20 16:18:23
    * 人脸识别-GET 请求(增加Header请求头) */ public class QdfsFaceToGetHttpHeader { public static void main(String[] args) { String url = "http://123.127.2.222:22111/recognizeRecords/top"; String ...
  • 使用HttpClient 添加header自定义参数

    千次阅读 2020-07-22 17:11:00
    try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(path); //添加header参数 httpPost.addHeader("Authorization","Bearer "+token); httpPost.addHeader("Content-Type",...
  • rabbitmq消费数据读取header中的值

    千次阅读 2019-05-27 21:40:35
    try { Object rawCorrelationId = properties.getHeaders().get(CORRELATION_ID_KEY); if(rawCorrelationId==null){ log.info("no correlationId provided in headers"); return null; } byte[] ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 232,458
精华内容 92,983
关键字:

headertry