How to make RESTful java client to send GET/POST r

2019-06-06 02:05发布

问题:

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"
        }
    }
}

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

          }

        }

    }

回答1:

I prefer Jersey API for REST calls;

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);

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));

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);