HTTP request headers and response headers for network programming

Source: Internet
Author: User
Tags comparison table response code

(i) overview
In the previous section, we learned about the network programming involved in Android, and also learned the basic concept of the next HTTP, and this section we want to learn is the HTTP request header and the response header;

(ii) HTTP request and Response headers
Here paste the previous section gives the diagram, according to the table given below, we feel the role of the relevant request head: PS: The first line is the request line: Request method + Resource name + HTTP protocol version number, in addition to the request header is only a message to the server or a simple, as to how to deal with, It's still up to the server!

HTTP Request header Information table:

Response header for 2.HTTP response:

同样给出上节的图: PS:第一行依次是:协议版本号 状态码 302表示这里没有,但是另外一个地方有,通过Location页面重定向了  

HTTP Responses Header Response Header information table:

3. Code verifies the role of the response header:

好了,看了那么多概念的东西,不动动手怎么行呢?是吧,那我们就写一些简单的代码来验证一些 常用的响应头的作用吧,以便加深我们的了解,这里的话服务端就用最简单的Servlet来实现,如果不会 Java Web的朋友只需将代码拷一拷,配置下web.xml,把Servlet的类名扣上,比如:  
<servlet>    <servlet-name>Firstservlet</servlet-name>    <servlet-class>Com.jay.server.FirstServlet</servlet-class></servlet><servlet-mapping>    <servlet-name>Firstservlet</servlet-name>    <url-pattern>/firstservlet</url-pattern></servlet-mapping>

Change to the corresponding class name!
1) page redirection via location

Implementation code:

ImportJava.io.IOException;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public  class servletone extends httpservlet {    @Override    protected void Doget(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {//Tell browser response code, and redirect pageResp.setstatus (302); Resp.setheader ("Location","Http://www.baidu.com"); }@Override    protected void DoPost(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException { This. Doget (req, resp); }}

Operation Result:

When we go to visit: Http://localhost:8080/HttpTest/ServletOne, we will find that the page jumps to Baidu, and then we use the Firefox developer tool: We can see the content of the HTTP we sent:

2) The compression format that tells the browser data via content-encoding

Implementation code:

ImportJava.io.ByteArrayOutputStream;ImportJava.io.IOException;ImportJava.util.zip.GZIPOutputStream;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public  class servlettwo extends httpservlet {    @Override    protected void Doget(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {String data ="Fresh Air and sunshine can have a amazing effect on our feelings."+"Sometimes when we were feeling down, all that we need to does is simply to go"+"Outside and breathe." Movement and exercise is also a fantastic the to feel better. "+"Positive emotions can be generated by motion. So if we start to feel down, "+"Take some deep breathes, go outside, feel the fresh air,"+"Let the Sun hits our face, go for a hike, a walk, a bike ride,"+"A swim, a run, whatever." We'll feel better if we do this. "; System.out.println ("raw Data length:"+ data.getbytes (). length);//Compress the data:Bytearrayoutputstream bout =NewBytearrayoutputstream (); Gzipoutputstream Gout =NewGzipoutputstream (bout);        Gout.write (Data.getbytes ()); Gout.close ();//Get Compressed data        byteGdata[] = Bout.tobytearray (); Resp.setheader ("Content-encoding","gzip"); Resp.setheader ("Content-length", Gdata.length +"");    Resp.getoutputstream (). write (Gdata); }protected void DoPost(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {doget (req, resp); };}

Operation Result:

Console output:

Browser output:

Take a look at our HTTP content:


This gzip compression string is inefficient for simple string compression;
3) Set the returned data type via Content-type

服务端返回的有时可能是一个text/html,有时也可能是一个image/jpeg,又或者是一段视频video/avi 浏览器可以根据这个对应的数据类型,然后以不同的方式将数据显示出来!好吧,这里我们弄一个读PDF的

Implementation code:

ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public  class servletthree extends httpservlet {    @Override    protected void Doget(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {resp.setheader ("Content-type","Application/pdf"); InputStream in = This. Getservletcontext (). getResourceAsStream ("/file/android coding specification. pdf");byteBuffer[] =New byte[1024x768];intLen =0; OutputStream out = Resp.getoutputstream (); while(len = in.read (buffer)) >0) {out.write (buffer,0, Len); }    }protected void DoPost(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {doget (req, resp); };}

Operation Result:

On the browser, type: Http://localhost:8080/HttpTest/ServletThree

Good da, sure enough to read the PDF, yes, this PDF I have been left in the Webroot file directory, or will be reported null pointer Oh ~:

Of course, you can also try to play a piece of music or video, just modify the next content-type this parameter

Below the way to give an HTTP content-type comparison table: HTTP content-type table

4) via Refresh response header, allow the browser to jump to other pages after a few seconds

Well, generally we may have such requirements, such as refreshing the page every few seconds, or loading a page a few seconds later to jump to another page, then refresh can meet your needs ~

Implementation code:

ImportJava.io.IOException;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public  class servletfour extends httpservlet {     Public intSecond =0;@Override    protected void Doget(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {//1. The browser refreshes the page every 2 seconds at regular intervals//Resp.setheader ("Refresh", "2");//Resp.getwriter (). Write (++second + "");//System.out.println ("Doget method is called ~");        //2. After entering page 5s, then the page jumps to Baidu ~Resp.setheader ("Refresh","5;url= ' http://www.baidu.com '"); Resp.getwriter (). Write ("He he da~"); }protected void DoPost(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {doget (req, resp); };}

Operation Result:

    1的话每隔2秒刷新一次页面,我们可以看到显示的数字是递增的,另外doGet方法也一直被调用, 说明页面真的是刷新的!    2的话进入页面后5s,就自己跳转到百度了~

5) Let the browser download the file via the Content-dispostion response header

这个很简单,我们只需把③中设置Content-type的一行去掉,然后加上: resp.setHeader("content-disposition", "attachment;filename=Android.pdf");

Implementation code:

ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public  class servletfive extends httpservlet {    @Override    protected void Doget(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {resp.setheader ("Content-disposition","Attachment;filename=android.pdf"); InputStream in = This. Getservletcontext (). getResourceAsStream ("/file/android coding specification. pdf");byteBuffer[] =New byte[1024x768];intLen =0; OutputStream out = Resp.getoutputstream (); while(len = in.read (buffer)) >0) {out.write (buffer,0, Len); }    }@Override    protected void DoPost(HttpServletRequest req, HttpServletResponse resp)throwsServletexception, IOException {doget (req, resp); }}

Operation Result:

This section introduces the request header and the response header in HTTP, as well as some examples of responses to the header browser, I believe that through this chapter, we have a better understanding of the HTTP protocol, the next section we will learn how Android provides us with the HTTP request method: httpurlconnection!

HTTP request headers and response headers for network programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.