anand
anand

Reputation: 1751

How to make RESTAPI calls in android using node.js

I have created a RESTAPI in Node.js and trying it to invoke into my android application. But i am not able to make the request to the Node.js Rest API.

My code are as follows:

Node.js

 var restify = require('restify');
 var request = require('request');
 var http    = require('http');
 var appContext = require('./config.js');

 function labsAPI(jsonparseStr) {
    return JSON.stringify(labsapi);
 }


 function searchbase(req, res, next){


    var options = {
        host: appContext.host,
        path: appContext.path+req.params.name+appContext.queryString
    };

   cbCallback = function(response) {
    var str = '';

    response.on('data', function (chunk) {
        str += chunk;
    });

    response.on('end', function () {
        jsonparseStr = JSON.parse(str);
        json_res = labsAPI(jsonparseStr);
        res.writeHead(200,{'Content-Type':'application/json'});
        res.end(json_res);
       });
   }
    http.request(options, cbCallback).end();
 }

  var server = restify.createServer({name:'crunchbase'});
  server.get('/search/:name',searchbase);

  server.listen(appContext.port, function() {
     console.log('%s listening at %s', server.name, server.url);
  });

After running my code like : localhost:8084/search/name

I am able to return the output to the browser a valid Json.

Now i want to consume this web service into my android application , I am not able to figure out how to do it. I tried some of the example http://hmkcode.com/android-parsing-json-data/

In the above blog in MainActivity.java i changed my url to

    new HttpAsyncTask().execute("http://127.0.0.1:8084/search/name");

but it is displaying nothing

Upvotes: 0

Views: 1636

Answers (1)

Kevin Sandow
Kevin Sandow

Reputation: 4033

127.0.0.1 is the IP address for localhost. From your browser localhost resolves to your computer, from your Android device localhost resolves to your Android device, but your node application isn't running on it.

You need to figure out what's your computer's remote address. LAN or WLAN would be enough as long as your on the same network as your Android device.

Also make sure firewall settings allow access to your computer.

Upvotes: 2

Related Questions