OKHttp3学习笔记-Http Get请求

来源:互联网 发布:淘宝号信誉等级查询 编辑:程序博客网 时间:2024/05/20 06:10

完成了环境搭建后,我的目的是对比用TP5实现的Web端访问生成的Http请求和用使用OKHttp3实现的Http请求都有哪些异同。在使用OKHttp3时,除了简单地Get/Post请求,要做文件上传时我们都在做什么。通过对比有一个直观的认识。
Get请求
php的Get请求:

GET http://localhost/index/index/dosubmit.html?fname=yang&lname=liu HTTP/1.1Host: localhostConnection: keep-aliveUpgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8Referer: http://localhost/index/index/indexAccept-Encoding: gzip, deflate, brAccept-Language: zh-CN,zh;q=0.8Cookie: pgv_pvi=6689128448; Phpstorm-ba9458cf=5f1ce810-71dc-4a40-821d-4699b7059873

OkHttp3实现的Get请求:

GET http://192.168.9.80/index/index/dosubmit.html?fname=yang&lname=liu HTTP/1.1Host: 192.168.9.80Connection: Keep-AliveAccept-Encoding: gzipUser-Agent: okhttp/3.8.1

上面这个是默认的OKHttp3做Get请求时的request信息,对应代码

val url = "http://192.168.9.80/index/index/dosubmit.html?fname=yang&lname=liu"val okHttpClient = OkHttpClient()val request = Request.Builder()    .url(url)    .build()val call = okHttpClient.newCall(request)call.enqueue(object: Callback{    override fun onFailure(p0: Call?, p1: IOException?) {    }    override fun onResponse(p0: Call?, p1: Response?) {    }})

可以发现默认的OKHttp3的Get请求和PHP的Get请求,Header有很大的不同,具体每个参数是什么意思可以参考这篇文章的链接:http://blog.csdn.net/theowl/article/details/47251197
但我们在使用的时候加入要完全模拟一个Web请求,就需自己去修改Header的参数,以User-Agent为例的话,就需要在构造request时,使用如下代码:

val request = Request.Builder()    .url(url)    .addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36")    .build()

这时的request请求就变成了

GET http://192.168.9.80/index/index/dosubmit.html?fname=yang&lname=liu HTTP/1.1User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36Host: 192.168.9.80Connection: Keep-AliveAccept-Encoding: gzip

所以OKHttp3提供给了我们一个非常简单的修改Header参数的方法。
但是了解HTTP协议Header参数的意思和常用值应该更重要一些。
下次在用PHP实现文件上传,然后在用OKHttp3实现一下对比来看看。