前言
写东西的时候遇到了带cookie访问的问题,就有了下文(okhttp或许是挺方便的吧
后面可能会写一个kotlin写爬虫的教程
完整步骤
因为需要携带cookie去操作,我们先简易封装一波okhttp:
import okhttp3.* import java.io.IOException class Http { companion object{ private var cookieStore: HashMap<String, List<Cookie>> = HashMap() // cookie拦截器,帮助我们携带cookie访问 private val Client = OkHttpClient.Builder() .cookieJar(object : CookieJar { override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) { cookieStore[url.host] = cookies } override fun loadForRequest(url: HttpUrl): List<Cookie> { val cookies = cookieStore[url.host] return cookies ?: ArrayList() } }) .build() private val NoCookieClient = OkHttpClient.Builder().build() fun post(url: String, body:Any, success: (Call, Response) -> Unit, error:(Call, IOException) -> Unit = {_,_ ->}){ val request = Request.Builder() .url(url) .post(body as RequestBody) .build() val call = Client.newCall(request) call.enqueue(object :Callback{ override fun onFailure(call: Call, e: IOException) { error(call, e) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { success(call, response) } }) } fun get(url: String, success: (Call, Response) -> Unit, error: (Call, IOException) -> Unit = { _, _ ->}) { val request = Request.Builder() .url(url) .get() .build() val call = Client.newCall(request) call.enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { error(call,e) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { success(call,response) } }) } } }
随后访问就完事了,这里给到的是带cookie访问
Post方式:
val LoginBody = FormBody.Builder() // post提交的数据 .add("email", "xxx") .add("passwd", "xxx") .build() Http.post("http://www.xxxxxx.com/auth/login",LoginBody, { _, response -> // 正常返回 val data:String = response.body!!.string() Log.d("Tag",data) }, { _, ioException -> // 输出错误 Log.d("Tag", ioException.toString()) })
Get方式:
Http.get("http://www.xxx.com/data",{ _, response -> // 正常返回 val data:String = response.body!!.string() Log.d("Tag",data) }, { _, ioException -> // 输出错误 Log.d("Tag", ioException.toString()) })
后记
做一波学习中的记录,再次感谢一波@gggxbbb的指导,如果有问题欢迎指出
转载请注明出处,本文链接:https://www.bokro.cn/79.html