gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:35:56 24 4
gpt4 key购买 nike

我想发出 POST 请求以从 Openstack 获取 token 。我可以通过输入 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();

}

}

}

最佳答案

我更喜欢 Jersey API 进行 REST 调用;

下面是获取POST实体中指定用户的token;

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 header ,以便对服务进行身份验证。

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

关于java - 如何让RESTful java客户端在Openstack上发送GET/POST请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37343072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com