2017-06-26 4 views
0

私はSpring Bootの新機能ですが、以前はHTTP OPTIONSコマンドでJavaを使用していました。Springヘッダーに資格情報を持つHTTP OPTIONSコマンドを実装するブート方法

私は、URLを受け取り、HTTP OPTIONSコマンドを使用してそのURLをテストするサービスメソッドを構築しています。

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(); 
      } 
     } 
} 

は、HTTP OPTIONS要求を実現するための春ブーツ同等の方法はありますか:以下

は、私はJavaを使用して書かれている何ですか?もしそうなら、要求の一部としてヘッダに資格(ユーザ名とパスワード)を追加することもできますか?ありがとう。

答えて

2

あなたは春ブーツの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)); 
} 

私はレスポンスボディタイプはこちらObjectを使用し、通常はオプション要求は何かを返しませんが、そうすることは禁止されていない、とexchangeメソッドはそこにクラスを持っていたい。私はslf4j Loggerを使って返されたヘッダを記録します。 httpsと基本認証を使用するサービスに対してテストされます。

関連する問題