使用HttpClient 4.5,根据httpclient示例,能够获取到返回的数据。根据示例类似的方式,调用openstack rest 接口,返回的是bad request。rest client测试时能够获取相关信息的。
不能获取的代码贴在下面, 后面再贴别人写得能获取的代码。
public void Authenticate(){
Auth auth = new Auth();
auth.setTenantName("admin");
auth.getPasswordCredentials().setUsername("admin");
auth.getPasswordCredentials().setPassword("123456");
CloseableHttpClient httpClient = HttpClients.createDefault();
String url = "http://10.133.0.223:5000/v2.0/tokens";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-type", "application/json");
// List<NameValuePair> var = new ArrayList<NameValuePair>();
// var.add(new BasicNameValuePair("\"auth\"", "{\"tenantName\": \"admin\",\"passwordCredentials\": {\"username\": \"admin\",\"password\": \"123456\"}}"));
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.setSerializationInclusion(Include.NON_EMPTY);
String str = null;
try {
str = objectMapper.writeValueAsString(auth);
} catch (JsonProcessingException e2) {
e2.printStackTrace();
}
try {
httpPost.setEntity(new ByteArrayEntity(str.toString().getBytes("UTF8")));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try {
HttpResponse httpResponse = httpClient.execute(httpPost, HttpClientContext.create());
//HttpResponse httpResponse = httpClient.execute(httpPost,"application/json");
//responseBody = httpClient.execute(httpPost, responseHandler);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(responseBody);
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
后面查了一下,出现bad request的原因是java对象转json对象,中间有个字段大小的错误,导致rest请求的参数错误,所以不能正确返回数据。
上面的代码其实是没有什么问题的。