关于HttpClient(调用openstack rest接口失败)

使用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请求的参数错误,所以不能正确返回数据。
上面的代码其实是没有什么问题的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值