I have a node js server implementation and I would like to send some values to an Android (Java) client. The method of the node js server is as follows:
app.get('/GetValues*', function (request, response) { // Request needs to be a GET if (request.method == 'GET') { var username = request.query.account; var time_now = Date.now(); var db = database('./database.db'); var row_account = db.prepare('SELECT SCORE score, STARTED_STUDY_SERVER_MILLIS timestamp, DAYS_TOTAL days_total FROM ACCOUNTS WHERE NAME = ?').get(username); var score = row_account.score; var days_total = row_account.days_total; var days_count = time_now - row_account.timestamp; var minutes_count = time_now - row_account.timestamp; var statement = db.prepare("UPDATE ACCOUNTS SET DAYS_COUNT = ?, MINUTES_COUNT = ? WHERE ID = ?"); statement.run(days_count,minutes_count,getAccountID(db, request.query.account)); var row_usage = db.prepare('SELECT DURATION_ENABLED duration_enabled, DURATION_DISABLED duration_disabled FROM USAGE WHERE NAME = ?').get(username); var duration_enabled = row_usage.duration_enabled; var duration_disabled = row_usage.duration_disabled; } });
I would like to send the values score
(integer), days_total
(integer), days_count
(integer), minutes_count
(long), duration_enabled
(long), duration_disabled
(long) to the client.
How can I send it to the client? I think response.send() only accepts strings. How can I parse the values in Java when received?
Advertisement
Answer
Since you need to send all those values at once, it’s common to respond with a JSON in such a case. In express, you can send a JSON response using response.send()
or response.json()
like this:
app.get('/GetValues*', function (request, response) { // ... your db operations here, then response.json({ score: score, days_total: days_total, days_count: days_count, minutes_count: minutes_count, duration_enabled: duration_enabled, duration_disabled: duration_disabled }); });
This will send a response with Content-Type: application/json
and a JSON string in the body looking like this:
{"score":12,"days_total":12,"days_count":12,"minutes_count":12,"duration_enabled":12,"duration_disabled":12}
Then you just parse it in your Java code.
By the way, this line
if (request.method == 'GET') {
is unnecessary. Registering a handler via app.get()
, express will only handle GET
requests anyway.