Search code examples
javatestingrest-assuredjava-http-client

Getting JSON data from server running on localhost


I'm trying to do some API testing but I'm not sure how to get started. Like in Java, how could I read in the response of a server for example:

localhost:3000/ping

the response is:

{
    "status": "success",
    "data": {
        "alive": true
    }
}

Looks like httpclient is no longer being developed, so I looked into REST-Assured (https://code.google.com/p/rest-assured/). My question is, how could I translate this to javacode? I was looking at httpclient, but I don't even know how to use it. Any help will be much appreciated, thanks much!

Screenshot:

enter image description here


Solution

  • import com.jayway.restassured.RestAssured.*;
    import com.jayway.restassured.matcher.RestAssuredMatchers.*;
    import org.hamcrest.Matchers.*;
    
    public class TestRest {
        public void doTest() {
            String json = given().port(3000).get("/ping").toString();
            System.out.println(json);
        }
    }
    

    To import library into maven:

    <dependency>
          <groupId>com.jayway.restassured</groupId>
          <artifactId>rest-assured</artifactId>
          <version>2.3.3</version>
          <scope>test</scope>
    </dependency>
    

    Edit

    To do this without static references:

    import com.jayway.restassured.RestAssured;
    
    public class testAPI {
        public void doTest() {
            String json = RestAssured.given().port(3000).get("/ping").toString();
            System.out.println(json);
        }
    }