Showing posts with label HTTP Request. Show all posts
Showing posts with label HTTP Request. Show all posts

Sunday, 9 December 2018

nodejs - call REST api with url encoded parameters

I have a REST API that expects url encoded request params as POST request body. So, API schema looks like
POST /login HTTP/1.1
Host: intro-api.com
Accept: */*
Content-Type: application/x-www-form-urlencoded
Content-Length: xxx
And, If you use curl request would look like,
curl -v --request POST -H "Content-Type: application/x-www-form-urlencoded" intro-api.com/login -d 'username=admin' -d 'password=admin'
Also, since content-type is urlencoded type, request params are in query string format. So -d "username=admin&password=admin" is valid as well.

Now,

I have a frontend(html/js) served by nodejs server which would have to validate user login by calling above REST api. This is what I'm talking in this article.
So, first of all I tried standard nodejs http library as a http client. But could not make it work for url encoded params. I was getting 408 error, which means it never sent the params?
function getUserSession(username, password) {

  const postData = qs.stringify({
    'username': username,
    'password': password
  });

  var options = {
    protocol: 'https:',
    host: 'intro.com',
    port: 443,
    path: '/login',
    method: 'POST',
    headers: {
      'Content-Type'  : 'application/x-www-form-urlencoded',
      'Content-Length': Buffer.byteLength(postData)
    }
  };

  https.request(options, function(resp){
    var response = '';
    resp.on('data', function(chunk){
      response += chunk;
      console.log(response)
    });
  }).on("error", function(e){
    console.log("Got error: " + e.message);
  });

}
So I ended up using request library. which needs to added to package.json (can also be done with npm install request, for more see official documentation).
Next, I will create auth.js with with a function that expects username and password and call the REST api, and respond the cookie value.
var request = require('request');

function getUserSessionId(username, password) {
  console.log("making login request")

  request.post({
    url: 'https://intro.com/login',
    form: {
      username: username,
      password: password
    }
  }).on("response", function(httpResponse) {
        var session = httpResponse.headers['set-cookie']
        console.log("session: " + session)
        return session
  });

}

var token = getUserSessionId('admin', 'admin')
Now, lets run it on terminal using node runtime (without having run it on http)
node auth.js
That is it to call "a REST api with url encoded params" using nodejs.

Friday, 28 April 2017

HTTP request headers


Check request header with cURL (see URL)
- cURL  is  a tool to transfer data from or to a server, using one of the supported protocols like HTTPS/ SMTPS/ gopher etc. see https://curl.haxx.se/


$ curl -v -XGET 172.24.14.158
* Rebuilt URL to: 172.24.14.158/
*   Trying 172.24.14.158...
* Connected to 172.24.14.158 (172.24.14.158) port 80 (#0)
> GET / HTTP/1.1
> Host: 172.24.14.158
> User-Agent: curl/7.43.0
> Accept: */*
> 
< HTTP/1.1 200 
< Content-Type: text/html;charset=ISO-8859-1
< Date: Sun, 30 Apr 2017 06:29:31 GMT
< Set-Cookie: JSESSIONID=C565042EC3A26A25D4ECF6787B54CE76;path=/;HttpOnly
< Content-Length: 14
< Connection: keep-alive
< 
some.her.data
* Connection #0 to host 172.24.14.158 left intact

Check request header with browser



Monday, 10 June 2013

logging HTTP Requests in Tomcat


[STEP 1] Add/Uncomment following Valve Component to conf/server.xml

<!-- Access log processes all example.
     Documentation at: /docs/config/valve.html
     Note: The pattern used is equivalent to using pattern="common" -->

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t %I &quot;%r&quot; %s %b" prefix="localhost_access_log." suffix=".txt"/>

where, %I = thread name
[STEP 2] cat GET requests
Only to count number of GET requests
$ cat apache-tomcat-6.0.26/logs/* | grep GET | wc -l
2238

To view all GET requests asynchronously (in production)
$ tail -f apache-tomcat-6.0.26/logs/* | grep GET --ignore-case
Mapped "{[/sessionexpired],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.zazzercode.eccount.server.controller.PaymentController.sessionExpired(org.springframework.ui.ModelMap)

In dev mode, using eclipse
$ tail -f eclipse_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/logs/* | grep GET


There also exists an Open source tool Java Melody for Tomcat Requests Monitoring.


                                                       Fig. Request Statistics


References
Best tools to monitor Tomcat, http://stackoverflow.com/a/1533254/432903