1

I am new to the Spring Boot, but I have worked with Java before on HTTP OPTIONS command.

I am building a service method that takes in an URL and test that URL using HTTP OPTIONS command.

Below is what I have written using Java:

import java.net.HttpURLConnection;
import java.net.URL;

    ...

public String testConnection(URL url) {
    try {
              String type = "text/plain;charset=UTF-8";
              HttpURLConnection conn = (HttpURLConnection) url.openConnection();

              conn.setDoOutput(true);
              conn.setRequestMethod("OPTIONS");
              conn.setRequestProperty("Content-Type", type);

              System.out.println(String.format("HTTP %d: %s",
                    conn.getResponseCode(), conn.getResponseMessage()));

              for(String header : conn.getHeaderFields().keySet() ){
                 System.out.println(String.format("%s : %s",
                       header, conn.getHeaderFields().get(header)));
              }

              String rMessage = conn.getResponseMessage();
              System.out.println ("Response " + rMessage);

           } catch (Exception e) {
              e.printStackTrace();
           }
        }
}

Is there a Spring Boot equivalent way of implementing the HTTP OPTIONS request? If so, could I also add credentials (username and password) to the header as part of the request? Thanks.

4

1 回答 1

3

You can use Spring Boot's RestTemplate:

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

// skipping class definition here, just showing the method call

private void optionsCall() {
    final String url = "https://some.server/with/some/path";
    final String user = "theUser";
    final String password = "thePassword";

    final String authHeaderValue = "Basic " + Base64.getEncoder()
            .encodeToString((user + ':' + password).getBytes());

    final HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Authorization", authHeaderValue);

    RestTemplate rest = new RestTemplate();
    final ResponseEntity<Object> optionsResponse =
            rest.exchange(url, HttpMethod.OPTIONS,
                    new HttpEntity<>(requestHeaders),
                    Object.class);

    optionsResponse.getHeaders().forEach((key, value) -> log.info("{} -> {}", key, value));
}

I use an Object here for the response body type, normally an OPTION request does not return something, but it is not forbidden to do so, and the exchange method wants to have a class there. I log the returned headers using an slf4j Logger. Tested against a service using https and basic authentication.

于 2017-06-27T07:26:23.160 回答