如何使RESTful Java客户端在Openstack上发送GET/POST请求? [英] How to make RESTful java client to send GET/POST request on Openstack?
问题描述
我想发出POST请求以从Openstack获取令牌. 我可以在Mozilla上使用插件,只需输入url:"http://*******/v2.0/tokens" 和数据为
I want to make a POST request to get token from Openstack. I am able to do so using an addon on Mozilla by entering url:"http://*******/v2.0/tokens" and data as
{
"auth": {
"tenantName": "admin",
"passwordCredentials": {
"username": "xxxxxx",
"password": "xxxxxx"
}
}
}
如何通过JAVA程序执行相同的操作? 到目前为止,我已经尝试了以下代码,但没有成功.
How to do same by JAVA program? Till now I have tried the following code, but with no success.
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调用;
I prefer Jersey API for REST calls;
以下是获取您的POST实体中指定用户的令牌;
Below one is to obtain token for specified user that is in your POST entity;
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)来解析您的实体.
Then you can parse your entity with some of parser such as com.google.gson.JsonParser.
JsonParser jsonParser = new JsonParser();
String responseEntity = jsonParser.parse(response.readEntity(String.class));
在此之后,对于每个请求,您都需要将X-Auth-Token应用于REST标头,以便对服务进行身份验证.
After that for each request , you need to apply X-Auth-Token to your REST header in order to authenticate for services.
jerseyInvocation.header("X-Auth-Token",token);
这篇关于如何使RESTful Java客户端在Openstack上发送GET/POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!