Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the open-source API Gateway Kong.
Do yourself a favor, and start making HTTP requests like this:
/**
* Unirest API call return jsonResponse handle
* Function Name: ApiCallFunction
* @param vEmail, Url
* @return status
*/
public static String ApiCallFunction(String vEmail, String Url) {
try{
HttpResponse<JsonNode> jsonResponse = Unirest.post(Url)
.field("vEmail",vEmail)
.asJson();
JSONObject output= jsonResponse.getBody().getObject();
String status= output.getString("status");
return status;
}catch(UnirestException e){
return "error";
}
}
Type Of Response Handle:
// Response to String
Sting bookResponse = Unirest.get(Url).asString();
//Response Basic Authentication
HttpResponse<JsonNode> jsonResponse = Unirest.get(Url).basicAuth("username", "password").asJson();
JSONObject output= jsonResponse.getBody().getObject();
//Response Object to Json
HttpResponse<JsonNode> jsonResponse = Unirest.post(Url)
.header("accept", "application/json")
.header("Content-Type", "application/json")
.body(authorObject)
.asJson();
JSONObject output= jsonResponse.getBody().getObject();
// Response to Object
HttpResponse<Book> bookResponse = Unirest.get(Url).asObject(Book.class);
Book bookObject = bookResponse.getBody();
// Response to Author
HttpResponse<Author> authorResponse = Unirest.get(Url)
.routeParam("id", bookObject.getId())
.asObject(Author.class);
Author authorObject = authorResponse.getBody();
Upon recieving a response Unirest returns the result in the form of an Object, this object should always have the same keys for each language regarding to the response details.
- getStatus() - HTTP Response Status Code (Example: 200)
- getStatusText() - HTTP Response Status Text (Example: "OK")
- getHeaders() - HTTP Response Headers
- getBody() - Parsed response body where applicable, for example JSON responses are parsed to Objects / Associative Arrays.
- getRawBody() - Un-parsed response body
Comments
Post a Comment