Servlets Client Request

5
http://www.tutorialspoint.com/servlets/servlets-client-request.htm Copyright © tutorialspoint.com SERV LETS - CLIENT HT T P REQUEST  Wh en a browse r req u e s ts for a web pag e , i t s e n ds lot of i n form ati on to t h e we b se rve r wh i ch can n ot be re ad dire ctl y be cause th is i n form ati on t rave l as a part of heade r of HT T P re qu e s t. You can chec k HTTP Protocol  f or more information on this. Fo ll owin g is th e im por tan t he ade r in format i on wh ich comes from brows e r s i de an d yo u w ould use ve ry fre quent ly in we b pro g ramm in g : Heade r Desc ription  Acce pt T h i s heade r spe cif i e s th e MIME types th at th e bro wse r or oth e r cli e n ts can h an dle. Valu e s of image/png  or image/jpeg  are the two most common possibilities.  Acce pt-Charse t T h i s heade r spe cif i e s th e c h aracte r se ts t h e bro wse r can u s e to di s pl ay t h e i n form ati on. Fo r e xam pl e ISO-8 85 9-1.  Acce pt-Encodi n g T h i s heade r spe cif i e s th e type s o f e n co di n g s th at th e br owse r kn ows how to h andle. Valu e s of gzip or compress are the two most common possibilities.  Acce pt-Lan g u ag e T h i s heade r spe cif i e s th e c l i e n t's prefe rre d l an g u ag e s in cas e th e s e rvlet can produ ce resu l ts in more th an on e la n g u ag e . For e xam pl e en , e n -us, ru, etc.  Au th orizati on T h i s heade r is use d by cl i e n ts t o i de n ti fy th e m se l ve s when acc e ss i n g password-prot ec t ed Web page s. Con ne ct ion Th i s he a der i n dicate s wh e the r th e cl i ent can han dl e per si s t ent HTTP connections. Persistent connections permit the client or other browser to re tri e ve m ul ti ple fil e s wi th a s i n g le re ques t. A val u e of Keep-Alive  mea n s that persistent connections should be used Con te n t - Le ng th Th i s header i s appl i cabl e on l y t o POST requ est s and gi ves t h e size of the POS T dat a i n bytes . C ooki e T h i s h eade r retu rns cookie s to s ervers th at pre vi ou s l y s e nt t h em t o t h e  brows e r. Hos t T h is h eader s pec i f i es t he h os t an d port as g ive n i n th e ori g i nal URL. If -Modi f i ed-Si nc e Th i s h ead er i n di cates t h at t h e cl i e nt wan t s t h e page on l y i f i t h as been ch an g e d af t e r th e spe cif i e d dat e . T h e se rver se n ds a c ode , 304 wh i ch means Not Mo dified header if no newer result is available. If -Unm odi f i ed-S i n ce Th i s h eader is t h e rev erse of If -Modi f i ed-Si nce; it speci f ies t h at t h e ope rati on shoul d s ucce e d onl y if th e doc um e n t i s olde r th an th e s pe cifi e d date. Re f e rer T his h e ader i n dic at es t h e URL of t he re f e rri n g We b page. For exam pl e , i f   you are at We b pag e 1 and click on a l i n k to Web pag e 2, th e U RL of Web pag e 1 is i n clu de d in th e Re fere r h e ader when th e br ows e r re ques ts We b pa g e 2. User- Ag e nt Th i s h eader ide nti f i es t h e browser or other c l ie n t m aki n g the re qu est and can be u s e d to re tu rn di ff e re n t cont e n t t o dif fere n t t ype s of brows e rs.

Transcript of Servlets Client Request

Page 1: Servlets Client Request

8/12/2019 Servlets Client Request

http://slidepdf.com/reader/full/servlets-client-request 1/4

http://www.tutorialspoint.com/servlets/servlets-client-request.htm Copyright © tutorialspoint.com

SERVLETS - CLIENT HTTP REQUEST

 When a browse r requests for a web pag e, it sends lot of information to the web se rver which can not be readdirectly because this information travel as a part of header of HTTP re quest. You can check HTTP Protocol formore information on this.

Following is the important header information which comes from browser s ide and you would use very fre quently in web prog ramming :

Header Description

 Acce pt This header spe cifies the MIME types that the browse r or other clients canhandle. Values of image/png  or image/jpeg  are the two most commonpossibilities.

 Acce pt-Charse t This header spe cifies the character se ts the browser can use to display theinformation. For example ISO-8859-1.

 Acce pt-Encoding This header spe cifies the types of encoding s that the browse r knows how tohandle. Values of gzip or compress are the two most commonpossibilities.

 Acce pt-Lang uag e This header spe cifies the client's preferred lang uag es in case the servletcan produce results in more than one lang uag e. For e xample en, en-us, ru,etc.

 Authorization This header is used by clients to identify themse lves when access ingpassword-protected Web page s.

C onne ction T his he ade r indicate s whe the r the clie nt can handle pe rs iste nt HT TPconnections. Persistent connections permit the client or other browser toretrieve multiple files with a sing le re quest. A value of Keep-Alive  meansthat persistent connections should be used

Content-Length This header is applicable only to POST requests and g ives the s ize of thePOST data in bytes.

Cookie This header returns cookies to servers that previously sent them to the browser.

Host This header specifies the host and port as g iven in the orig inal URL.

If-Modified-Since This header indicates that the client wants the page only if it has beenchang ed after the spe cified date. The se rver se nds a code, 304 whichmeans Not Modified header if no newer result is available.

If-Unmodified-Since This header is the reverse of If-Modified-Since; it specifies that theope ration should succe ed only if the document is older than the specifieddate.

Referer This header indicates the URL of the referring Web pag e. For example, if   you are at Web page 1 and click on a link to Web pag e 2, the URL of Webpag e 1 is included in the Re fere r header when the browser requests Webpag e 2.

User-Ag e nt T his he ade r ide ntifie s the browser or othe r clie nt making the re que st andcan be used to re turn different content to differe nt types of browsers.

Page 2: Servlets Client Request

8/12/2019 Servlets Client Request

http://slidepdf.com/reader/full/servlets-client-request 2/4

Methods to read HTTP Header:

There are following methods which can be used to read HTTP header in your servlet prog ram. These methodsare available with HttpServletRequest  object.

S.N. Method & Description

1 Cookie[] g etCookies()

Returns an array containing all of the Cookie obj ects the client sent with this request.

2 Enumeration g etAttributeNames()Returns an Enumeration containing the names of the attributes available to this request.

3 Enumeration g etHeaderNames()Returns an enumeration of all the header names this request contains.

4 Enumeration g etParameterNames()Returns an Enumeration of String obj ects containing the names of the parameters contained in thisrequest.

5 HttpSession g etSession()Returns the current session ass ociated with this request, or if the request does not have a session,creates one.

6 HttpSession getSession(boolean create)Returns the current HttpSession associated with this request or, if if there is no current session andcreate is true, returns a new session.

7 Loc ale g etLocale()Returns the preferre d Locale that the client will acce pt content in, based on the Acce pt-Lang uag eheader

8 Object g etAttribute(String name)Returns the value of the named attribute as an Object, or null if no attribute of the g iven name exists.

9 ServletInputStream g etInputStream()Retrieves the body of the request as binary data using a Se rvletInputStream.

10 String getAuthType()Returns the name of the authentication scheme used to protect the servlet, for example, "BASIC" or"SSL," or null if the JSP was not protected

11 String getCharacterEncoding()Returns the name of the character e ncoding used in the body of this request.

12 String getContentType()Returns the MIME type of the body of the request, or null if the type is not known.

13 String getContextPath()Returns the portion of the request URI that indicates the context of the request.

14 String g etHeader(String name)Returns the value of the specified request header as a String .

15 String getMethod()Returns the name of the HTTP method with which this request was made, for example, GET, POST,or PUT.

16 String getParameter(String name)Returns the value of a re quest parameter as a String , or null if the parameter does not exist.

17 String g etPathInfo()Returns any extra path information associated with the URL the client se nt when it made this request.

Page 3: Servlets Client Request

8/12/2019 Servlets Client Request

http://slidepdf.com/reader/full/servlets-client-request 3/4

18 String getProtocol()Returns the name and version of the protocol the request.

19 String g etQueryString ()Returns the query string that is contained in the request URL after the path.

20 String getRemoteAddr()Returns the Internet Protocol (IP) address of the client that sent the request.

21 String getRemoteHost()Returns the fully qualified name of the client that sent the request.

22 String g etRemoteUser()Returns the log in of the user making this request, if the user has been authenticated, or null if the userhas not be en authenticated.

23 String g etRequestURI()Returns the part of this re quest's URL from the protocol name up to the query string in the first line of the HTTP request.

24 String g etRequestedSessionId()

Returns the session ID specified by the client.

25 String g etServletPath()Returns the part of this request's URL that calls the JSP.

26 String[] getParameterValues(String name)Returns an array of String obj ects containing all of the values the g iven request parameter has, or nullif the parameter does not exist.

27  boolean isSec ure()Returns a boolean indicating whether this request was made using a secure channel, such as HTT PS.

28 int g etContentLeng th()

Returns the length, in bytes, of the request body and made available by the input stream, or -1 if theleng th is not known.

29 int getIntHeader(String name)Returns the value of the specified request header as an int.

30 int g etServerPort()Returns the port number on which this request was received.

HTTP Header Request Example:

Following is the example which uses getHeaderNames() method of HttpServletRequest to re ad the HTT Pheader infromation. This method returns an Enumeration that contains the header information associated with thecurrent HTTP request.

Once we have an Enumeration, we can loop down the Enumeration in the standard manner, usinghasMoreElements() method to determine when to s top and using nextElement() method to g et each parametername.

// Import required java libraries

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*; 

// Extend HttpServlet class

public class DisplayHeader extends HttpServlet {

 

// Method to handle GET method request.

  public void doGet(HttpServletRequest request,

Page 4: Servlets Client Request

8/12/2019 Servlets Client Request

http://slidepdf.com/reader/full/servlets-client-request 4/4

  HttpServletResponse response)

  throws ServletException, IOException

  {

  // Set response content type

  response.setContentType("text/html");

 

PrintWriter out = response.getWriter();

  String title = "HTTP Header Request Example";

  String docType =

  "<!doctype html public \"-//w3c//dtd html 4.0 " +

  "transitional//en\">\n";

  out.println(docType +

  "<html>\n" +

  "<head><title>" + title + "</title></head>\n"+

  "<body bgcolor=\"#f0f0f0\">\n" +

  "<h1 align=\"center\">" + title + "</h1>\n" +

  "<table width=\"100%\" border=\"1\" align=\"center\">\n" +

  "<tr bgcolor=\"#949494\">\n" +

  "<th>Header Name</th><th>Header Value(s)</th>\n"+

  "</tr>\n");

 

Enumeration headerNames = request.getHeaderNames();

 

while(headerNames.hasMoreElements()) {

  String paramName = (String)headerNames.nextElement();

  out.print("<tr><td>" + paramName + "</td>\n");

  String paramValue = request.getHeader(paramName);

  out.println("<td> " + paramValue + "</td></tr>\n");

  }

  out.println("</table>\n</body></html>");

  }

  // Method to handle POST method request.

  public void doPost(HttpServletRequest request,

  HttpServletResponse response)

  throws ServletException, IOException {

  doGet(request, response);

  }

}

Now calling the above servlet would g enerate following result:

HTTP HEADER REQUEST EXAMPLE

Header Name Header Value(s)

accept */*

accept-lang uag e en-us

user-ag ent Mozilla/4.0 (compatible ; MSIE 7.0; Windows NT 5.1; T ride nt/4.0;InfoPath.2; MS-RT C LM 8)

accept-encoding g zip, deflate

host localhost:8080

connection Keep-Alive

cache-control no-cache