【问题标题】:How to make RESTful java client to send GET/POST request on Openstack?如何让 RESTful java 客户端在 Openstack 上发送 GET/POST 请求?
【发布时间】:2016-09-17 12:07:55
【问题描述】:

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

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

          }

        }

    }

【问题讨论】:

标签: java rest post openstack restful-authentication


【解决方案1】:

我更喜欢 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);

【讨论】:

    猜你喜欢
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多