如何使用springframework/spring-boot的RestTemplate在Firebase Remote Config REST API的实现中获取“etag”?

i5desfxk  于 2023-04-20  发布在  Spring
关注(0)|答案(1)|浏览(110)

我在一个Android应用的spring-boot服务器中实现了firebase-remote-config rest API,用于学习。我的spring boot版本是 2.1.7.RELEASE。我试图获取 etag 值,以便从服务器端更新key & values,不使用firebase控制台。我能够通过httpconnection获得 etag,就像这个link一样。但是每当我使用 RestTemplate 时,我都无法获得 etag,我得到的是null
这是 build.gradle 文件

buildscript {
    ext {
        springBootVersion = '2.1.7.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.practice.shaikhalvee'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
    compile group: 'com.google.apis', name: 'google-api-services-firebaseremoteconfig', version: 'v1-rev14-1.23.0'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.5'
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.6'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

这是我创建的用于试验firebase-remote-config的控制器。

@RestController
@RequestMapping(value = "/api/remote-config")
public class FirebaseRestApiEndpoint {

    private final FirebaseRemoteConfigService firebaseRemoteConfigService;

    public FirebaseRestApiEndpoint(FirebaseRemoteConfigService firebaseRemoteConfigService) {
        this.firebaseRemoteConfigService = firebaseRemoteConfigService;
    }

    @GetMapping(value = "/get-template/{call-type}")
    public void getTemplate(@PathVariable("call-type") String callType) {
        switch (callType) {
            case "http":
                firebaseRemoteConfigService.getMetadataTemplateWithHttpCall();
                break;
            case "rest":
                firebaseRemoteConfigService.getMetadataTemplateWithRestCall();
                break;
            default:
                throw new RuntimeException("call-type is unknown. Should be rest or http");
        }
    }
}

这是我使用的accessToken()进程

// Constant File holds the url and other static final string values.
public static String getAccessToken() throws IOException {
    GoogleCredential googleCredential = GoogleCredential
            .fromStream(new FileInputStream(Constants.CERTIFICATE_FILE))
            .createScoped(Arrays.asList(Constants.SCOPES));
    googleCredential.refreshToken();
    return googleCredential.getAccessToken();
}

对于服务层,为了简化,我只包括这里调用的方法。
这是使用HttpUrlConnection的方法。

public void getMetadataTemplateWithHttpCall() {
    try {
        URL url = new URL(Constants.BASE_URL + Constants.REMOTE_CONFIG_ENDPOINT);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestProperty("Authorization", "Bearer " + CommonConfig.getAccessToken());
        httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setRequestProperty("Accept-Encoding", "gzip");

        int code = httpURLConnection.getResponseCode();
        if (code == 200) {
            InputStream inputStream = new GZIPInputStream(httpURLConnection.getInputStream());
            JsonElement jsonElement = JsonParser.parseReader(new InputStreamReader(inputStream));

            Gson gson = new GsonBuilder()
                    .setPrettyPrinting()
                    .disableHtmlEscaping()
                    .enableComplexMapKeySerialization()
                    .serializeSpecialFloatingPointValues()
                    .create();
            String jsonStr = gson.toJson(jsonElement);
            RemoteConfig remoteConfig = gson.fromJson(jsonStr, RemoteConfig.class);
            String etag = httpURLConnection.getHeaderField("ETag");
            System.out.println(etag);
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}

在这里,根据Firebase-Remote-Config REST API的documentation打印适当的etag。
但是如果我尝试用RestTemplate实现相同的http get连接,我就无法获得 etag
现在这是使用RestTemplate的方法。我为这个rest调用提供了非常相似的请求属性。但我仍然无法获得 etag

public void getMetadataTemplateWithRestCall() {
    ObjectMapper objectMapper = new ObjectMapper();
    HttpHeaders httpHeaders = new HttpHeaders();
    String url = "";
    try {
        httpHeaders.add(HttpHeaders.CONTENT_ENCODING, "gzip");
        httpHeaders.setBearerAuth(CommonConfig.getAccessToken());
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);

        url = Constants.BASE_URL + Constants.REMOTE_CONFIG_ENDPOINT;

        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);
        ResponseEntity<RemoteConfig> baseResponse = restTemplate.exchange(url, HttpMethod.GET, requestEntity, RemoteConfig.class);

        String etag = baseResponse.getHeaders().getETag();
        System.out.println(etag);
    } catch (IOException e) {
        e.getMessage();
    }
}

正如你所猜测的,这个 etag 值是null。我正在尝试Firebase远程配置REST调用,但是如果我不能正确处理REST调用,也许我在这里遗漏了一些东西。
为了您的方便,我提供了他们的头,因为 etag 驻留在头中。* 有趣的事实,在http调用中,我得到13个头。在rest调用中,我得到11个。你猜对了,etag不见了 *
这是HTTP连接调用的标头。

Transfer-Encoding=[chunked], 
null=[HTTP/1.1 200 OK],
Alt-Svc=[quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000], 
Server=[ESF], 
X-Content-Type-Options=[nosniff], 
Date=[Mon, 11 Nov 2019 04:59:04 GMT], 
X-Frame-Options=[SAMEORIGIN], 
Cache-Control=[private], 
ETag=[etag-111111311162-47],
Content-Encoding=[gzip],
Vary=[Referer, X-Origin, Origin], 
X-XSS-Protection=[0], 
Content-Type=[application/json; charset=UTF-8]

这是Rest Call的标头

Content-Type:"application/json; charset=UTF-8", 
Vary:"X-Origin", "Referer", "Origin,Accept-Encoding", 
Date:"Mon, 11 Nov 2019 05:15:10 GMT", 
Server:"ESF", 
Cache-Control:"private", 
X-XSS-Protection:"0", 
X-Frame-Options:"SAMEORIGIN", 
X-Content-Type-Options:"nosniff", 
Alt-Svc:"quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000", 
Accept-Ranges:"none", 
Transfer-Encoding:"chunked"

我的目标是使用rest调用获取 etag 值,更准确地说是使用 springframework 的RestTemplate,因为它是一个REST API。
谢谢大家。

velaa5lx

velaa5lx1#

经过长时间的研究和调试,我找到了一个解决方案。
在文档中,我们被告知添加headerAccept-Encoding:gzip.所以我在getMetadataTemplateWithHttpCall()方法中使用了httpHeaders.add(HttpHeaders.CONTENT_ENCODING, "gzip");.它不起作用.我甚至添加了这样的头,httpHeaders.add("Accept-Encoding", "gzip");.它抛出异常,RestTemplate不接受gzip作为 Accept-Encoding。有效的方法是,如果在调用之前使用自定义的RestTemplate拦截器拦截rest调用,并使用拦截器使用gzip压缩请求。这意味着在RestTemplate的情况下,我们需要在http调用之前压缩请求,然后发送它。只有这样,在 ResponseEntity 中,我才能得到“etag”。
我已经为指定的RestTemplate创建了一个@Bean,我在下面提供了。如果你想使用springframework的RestTemplate,那么你必须添加这种类型的拦截器来使用Firebase Remote Config REST API。
这是@Bean

@Configuration
public class RestTemplateConfig {
    @Bean(value = "gzippedRestTemplate")
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
                HttpClientBuilder.create().build());
        clientHttpRequestFactory.setConnectTimeout(2000);
        clientHttpRequestFactory.setReadTimeout(10000);
        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
        List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
        if (interceptors == null) {
            interceptors = new ArrayList<>();
            restTemplate.setInterceptors(interceptors);
        }
        interceptors.add(new GzipAcceptHeaderRequestInterceptor());
        return restTemplate;
    }
    public static class GzipAcceptHeaderRequestInterceptor implements ClientHttpRequestInterceptor {
        @Override
        public ClientHttpResponse intercept(HttpRequest request, @Nullable byte[] body, ClientHttpRequestExecution execution) throws IOException {
            request.getHeaders().set(HttpHeaders.ACCEPT_ENCODING, "gzip");
            return execution.execute(request, body);
        }
    }
}

现在你可以使用springframework的RestTemplate从GET调用中获取“etag”值,发布你的作品。

相关问题