如何让RESTful java客户端在Openstack上发送GET / POST请求?

时间:2016-05-20 09:32:27

标签: java rest post openstack restful-authentication

我想发一个POST请求来从Openstack获取令牌。 我可以通过输入url在Mozilla上使用插件来实现:" http://*******/v2.0/tokens" 和数据

{
    "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();

          }

        }

    }

1 个答案:

答案 0 :(得分:0)

我更喜欢Jersey API用于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-Token应用于REST标头,以便对服务进行身份验证。

jerseyInvocation.header("X-Auth-Token",token);