http原理浅谈:使用socket实现最简单的http大框架

现在市面上有许多流行的http框架,其实到底层还是利用了socket。大家都学过TCP/IP的四层协议吧。其实http属于应用层,而socket则在网络层。所以http最后肯定要调用socket的。哈哈哈

http原理浅谈:使用socket实现最简单的http大框架_第1张图片
TCP/IP.png

。下面例子展示了最简单的http框架,看http是怎么调用到socket的。

package com.example.sockethttp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.io.BufferedWriter;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button getbt;
    private TextView resulttv;
    private Lihttpclent mclient;
    private static  final String TAG ="wenfeng";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getbt=(Button)findViewById(R.id.Getbt);
        resulttv=(TextView)findViewById(R.id.Result);
        getbt.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        mclient=new Lihttpclent("www.youku.com");
        String response=mclient.excute();
        resulttv.setText(response);
    }


    class Lihttpclent{
        private String innersite;
        private StringBuilder mbuild = new StringBuilder("");
        public Lihttpclent(String site){
            this.innersite=site;
        }


        public String excute() {

          Thread getthread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Log.i(TAG,"start run");
                        Socket mSocket=new Socket(
                                InetAddress.getByName(innersite),
                                80);
                        BufferedReader  br = new BufferedReader(new
                                InputStreamReader(
                                mSocket.getInputStream(),"utf-8"));
                        BufferedWriter bf = new BufferedWriter((new OutputStreamWriter(
                                mSocket.getOutputStream())));
                        StringBuffer requestHeader = new StringBuffer();
                        requestHeader
                                .append("GET " + "/"
                                        + " HTTP/1.1\n")
                                .append("HOST:" + innersite + "\n")
                                //.append("Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\n")
                                .append("Accept-Encoding:gzip, deflate, sdch\n")
                                .append("Accept-Language:zh-CN,zh;q=0.8\n")
                                .append("Cache-Control:no-cache\n")
                                .append("User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36\n")
                                .append("Encoding:UTF-8\n")
                                .append("Connection:keep-alive" + "\n")
                                .append("\n");

                        bf.write(requestHeader.toString());
                        bf.flush();
                        String line = "";
                        Log.i(TAG,"start read response");
                        while((line=br.readLine())!=null)
                        {
                                mbuild.append(line);
                                mbuild.append("\r\n");
                        }
                        Log.i(TAG,mbuild.toString());
                    }catch (Exception e){
                        Log.i(TAG,"excetion = "+e.toString());
                    }

                }
            });
            getthread.start();
            try {
                getthread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.i(TAG,"outbuilder="+mbuild.toString());
            return mbuild.toString();
        }
    }

}

一般的框架给程序员的接口都很简单,输入参数一般是个网址就可以了,上面的例子也是这样,上面例子的框架类是Lihttpclent,为了简单说明原理,输入参数就一个String类型的网址,是不是很简单呢?

        mclient=new Lihttpclent("www.youku.com");
        String response=mclient.excute();

他是怎么跟socket联系在一起的呢?
1.socket构建需要ip地址和端口,所以可以通过InetAddress将网址转换为ip,端口写死80就好。

                        Socket mSocket=new Socket(
                                InetAddress.getByName(innersite),
                                80);

2.那现在socket通道构建起来,该给服务器发些啥呢?那就参照http协议罗,协议要啥就发啥,发一个符合http协议的字符串过去就行了,信息包含编码,缓存,语言等,那服务器就会响应你了。

                        StringBuffer requestHeader = new StringBuffer();
                        requestHeader
                                .append("GET " + "/"
                                        + " HTTP/1.1\n")
                                .append("HOST:" + innersite + "\n") 
                                .append("Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\n")                         
                                .append("Accept-Encoding:gzip, deflate, sdch\n")
                                .append("Accept-Language:zh-CN,zh;q=0.8\n")
                                .append("Cache-Control:no-cache\n")
                                .append("User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36\n")
                                .append("Encoding:UTF-8\n")
                                .append("Connection:keep-alive" + "\n")
                                .append("\n");

3.开启一个线程跟服务器通信,然后获取服务器的响应,将响应的字符串显示在界面

    @Override
    public void onClick(View v) {
        mclient=new Lihttpclent("www.youku.com");
        String response=mclient.excute();
        resulttv.setText(response);
    }

点击get按钮后,等待一下,界面上显示如下

http原理浅谈:使用socket实现最简单的http大框架_第2张图片
返回值.jpg

例子的源码路径是下面链接,大家可以体会下,其实http框架的基本原理就是这样。当然缓存机制,连接池机制等都是修饰这个大框架的,而衡量框架是否优秀就是看这些修饰了O(∩_∩)O~~。
https://github.com/wenfengtou/SocketHttpDemo

你可能感兴趣的:(http原理浅谈:使用socket实现最简单的http大框架)