Web Development - Make HTTP Request
This post keeps updating as my learing going on.
To make a http request, the basic procedure is as follows:
- Prepare URL, data, action that are passed to the server;
- Define response handler or callback function to handle the response;
- New a http request or client;
- Send the request to server; Because most of the response handling is asynchronously, so the response handler function need to defined before.
Asynchronous and Synchronous Request
If you use asynchronous request, you receivea callback when the data has been received. This lets the browser continue to word as normal whilc the request is being handled.
Synchronous request offer cause hangs on the web, the recommendation is use asynchronous request.
JavaScript
AJAX
AJAX is Asychronous Javascript And XML. It uses XMLHTTPRequst to send http request. Basic procedure is:
- Prepare a URL, method, and response handler, error handle function.
- New a XMLHttpRequest();
- Open the request.
- If no data need to send, just send it, else set request header, and send data.
- Handler the reponse information. Example below:
// passed in paramenter should include the method, url, data, success and error callback function.
function ajax(opt) {
var opt = opt || {},
method = (opt.method || 'GET').toUpperCase(),
url = opt.url,
data = opt.data || null,
success = opt.success || function () {},
error = opt.error || function() {},
xhr = new XMLHttpRequest(); // new a XMLHttpRequest object;
if (!url) {
throw new Error('Missing URL');
}
xhr.open(method, url, true); //open
if (!data) {
xhr.send(); // send without data
} else {
// send data in
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.send(JSON.stringify(data));
}
// response handler
xhr.onload = ()=> {
if (xhr.status === 200) {
success(JSON.parse(xhr.responseText))
} else {
error();
}
}
// error handler
xhr.onerror = ()=> {
throw new Error('The request could not be completed');
}
}
JQuery
JQuery simplify the above code a little bit, but basiclly similar. It encapsulate a ajax function and pass in a JSON object with action, url, data, etc. Example:
//POST method
$.ajax({
type: "POST",
url: "https://www.google.com",
data: data,
success: successCB,
error: errorCB,
dataType: dataType
});
$.ajax({
type: "GET",
url: "",
data: data,
}).done(function(data) {
// do something with the data
}).fail(function(){
// do something on error
})
Fetch
Fetch somehow replace XMLHttpRequest and easier than XMLHttpRequest.
Example:
//Get
fetch(url).then(
data => {
// do something with data
}
).catch(error =>{
//error handler
})
//POST
fetch(url, {
method: 'POST',
header: { }, //set header
body: { }, //set body data
}).then(
res => { } //response handler
)
Axios
Another way to make http request, very similary to fetch and ajax method. Example:
//GET
axios({
url:'https://google.com',
method: 'GET'
})
//POST
axios.post(url, {
header: { }, //set header
body: { }, //set body data
}).then(
res => { } //response handler
).catch (
error => { } //error handler
)
Java
Apache HttpClient
This is what I’ve used so far.
// put keyword, lat, and lon to URL.
String url = String.format(URL_TEMPLATE, keyword, lat, lon);
// create http client
CloseableHttpClient httpclient = HttpClients.createDefault();
// create response interface using lambda expression (anonymous class)
ResponseHandler<List<Item>> responseHandler = response -> {
// test response status code
if (response.getStatusLine().getStatusCode() != 200) {
return Collections.emptyList();
}
// get response content
HttpEntity entity = response.getEntity();
if (entity == null) {
return Collections.emptyList();
}
// map the content to class Item
ObjectMapper mapper = new ObjectMapper();
// return Arrays.asList(mapper.readValue(entity.getContent(), Item[].class));
List<Item> items = Arrays.asList(mapper.readValue(entity.getContent(), Item[].class));
// extract keywords from all the items
extractKeywords(items);
return items;
};
// send to url and get response
try {
return httpclient.execute(new HttpGet(url), responseHandler); //sync request
} catch (IOException e) {
e.printStackTrace();
}