2016-05-20 3 views
1

Openstackからトークンを取得するPOSTリクエストを作成したいとします。 私はURLを入力してMozillaにアドオンを使用してそうすることができる午前:「のhttp://*******/v2.0/tokens」OpenStackでGEST/POSTリクエストを送信するRESTfulなJavaクライアントを作成するには?

行う方法
{ 
    "auth": { 
     "tenantName": "admin", 
     "passwordCredentials": { 
      "username": "xxxxxx", 
      "password": "xxxxxx" 
     } 
    } 
} 

として とデータをJAVAプログラムでも同じですか? これまで、次のコードを試しましたが、成功しませんでした。

package rest.openstack; 

    import java.io.BufferedReader; 
    import java.io.IOException; 
    import java.io.InputStreamReader; 
    import java.net.HttpURLConnection; 
    import java.net.MalformedURLException; 
    import java.net.URL; 

    public class NetClientGet { 

     // http://localhost:8080/RESTfulExample/json/product/get 
     public static void main(String[] args) { 

      try { 

      URL url = new URL("http://***.**.**.**:5000/v2.0/tenants/"); //url for openstack 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setRequestMethod("GET"); 
      conn.setRequestProperty("Accept", "application/json"); 

      if (conn.getResponseCode() != 200) { 
       throw new RuntimeException("Failed : HTTP error code : " 
         + conn.getResponseCode()); 
      } 

      BufferedReader br = new BufferedReader(new InputStreamReader(
       (conn.getInputStream()))); 

      String output; 
      System.out.println("Output from Server .... \n"); 
      while ((output = br.readLine()) != null) { 
       System.out.println(output); 
      } 

      conn.disconnect(); 

      } catch (MalformedURLException e) { 

      e.printStackTrace(); 

      } catch (IOException e) { 

      e.printStackTrace(); 

      } 

     } 

    } 
+0

なぜJava SDKのいずれかをhttps://wiki.openstack.org/wiki/SDKs#Javaから使用しないでください。 –

答えて

0

私はJersey API for RESTコールを使用することをお勧めします。

以下は、POSTエンティティにある特定のユーザーのトークンを取得することです。

String postEntity = "yourJson"; 
JerseyClient jerseyClient = JerseyClientBuilder.createClient(); 
JerseyWebTarget jerseyTarget = jerseyClient.target("http://***.**.**.**:****/v2.0/tokens"); 
JerseyInvocation.Builder jerseyInvocation = jerseyTarget.request("application/json"); 
jerseyInvocation.header("Context-type", "application/json"); 
Response response = jerseyInvocation.post(Entity.entity(postEntity, MediaType.APPLICATION_JSON), Response.class); 

次に、com.google.gson.JsonParserなどのパーサーでエンティティを解析できます。

JsonParser jsonParser = new JsonParser(); 
String responseEntity = jsonParser.parse(response.readEntity(String.class)); 

その後、リクエストごとに、サービスの認証を行うためにX-AuthトークンをRESTヘッダーに適用する必要があります。

jerseyInvocation.header("X-Auth-Token",token); 
関連する問題