- An HttpClient can be used to send requests and retrieve their responses
- An HttpRequest sets up header and body to API provider
- An HttpResponse is returned as a result of sending an HttpRequest
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://hotels4.p.rapidapi.com/v2/get-meta-data"))
.header("x-rapidapi-key", "80afb5b6afmsh552d92e769ba3a5p1bfac9jsnfb6c407dd20f")
.header("x-rapidapi-host", "hotels4.p.rapidapi.com")
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
//RapidAPI request and response
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
//RapidAPI Body
System.out.println(response.body());
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Date;
import java.util.HashMap;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController // annotation to create a RESTful web services
@RequestMapping("/api/flights") //prefix of API
public class flights {
private JSONObject body; //last run result
private HttpStatus status; //last run status
String last_run = null; //last run day of month
@GetMapping("/monthly") //added to end of prefix as endpoint
public ResponseEntity<JSONObject> flights() {
//calls API once a day, sets body and status properties
String today = new Date().toString().substring(0,500);
if (last_run == null || !today.equals(last_run))
{
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://hotels4.p.rapidapi.com/v2/get-meta-data"))
.header("x-rapidapi-key", "80afb5b6afmsh552d92e769ba3a5p1bfac9jsnfb6c407dd20f")
.header("x-rapidapi-host", "hotels4.p.rapidapi.com")
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
//RapidAPI request and response
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
//JSONParser extracts text body and parses to JSONObject
this.body = (JSONObject) new JSONParser().parse(response.body());
this.status = HttpStatus.OK; //200 success
this.last_run = today;
}
catch (Exception e) { //capture failure info
HashMap<String, String> status = new HashMap<>();
status.put("status", "RapidApi failure: " + e);
//Setup object for error
this.body = (JSONObject) status;
this.status = HttpStatus.INTERNAL_SERVER_ERROR; //500 error
this.last_run = null;
}
}
//return JSONObject in RESTful style
return new ResponseEntity<>(body, status);
}
}