httpURLConnection 基本使用

前言

为了测试,不想引入retrofit或者okhttp,就用普通的网络请求一下。

简单封装

class AsyncTaskUtils(private val mParam: String, private val mCallBack: NetCallback?) :
    AsyncTask<Void?, Void?, String?>() {

     override fun doInBackground(vararg param: Void?): String? {
        try {
            val httpURLConnection =
                URL(CHECK_MAC).openConnection() as HttpsURLConnection
            httpURLConnection.requestMethod = "POST" // 提交模式
            httpURLConnection.connectTimeout = 1 * 1000 //连接超时 单位毫秒
            httpURLConnection.readTimeout = 1 * 1000 //读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.doOutput = true
            httpURLConnection.doInput = true
            //   设置请求类型 
            httpURLConnection.setRequestProperty(
                "Content-type",
                "application/x-www-form-urlencoded;charset=UTF-8" // form表单(json:application/json)
            )
            // 设置headers
            httpURLConnection.setRequestProperty("app_id", "xxxxxxx")
            httpURLConnection.setRequestProperty("token", "xxxxxxx")

            // 获取URLConnection对象对应的输出流
            val printWriter =
                PrintWriter(httpURLConnection.outputStream)
            // 发送请求参数
            printWriter.write(mParam) //post的参数
            // flush输出流的缓冲
            printWriter.flush()
            // 开始获取数据
            val bis =
                BufferedInputStream(httpURLConnection.inputStream)
            val bos = ByteArrayOutputStream()
            var len: Int
            val arr = ByteArray(1024)
            while (bis.read(arr).also { len = it } != -1) {
                bos.write(arr, 0, len)
                bos.flush()
            }
            bos.close()
            return bos.toString("utf-8")
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    override fun onPreExecute() {
        super.onPreExecute()
    }

    override fun onPostExecute(response: String?) {
        super.onPostExecute(response)
        if (mCallBack != null) {
            if (response != null) {
                mCallBack.onSuccess(response)
            } else {
                mCallBack.onFailure()
            }
        }
    }

    companion object {
        private const val CHECK_MAC = "https://baidu.com"
        fun map2Url(paramToMap: Map<String?, String?>?): String? {
            if (null == paramToMap || paramToMap.isEmpty()) {
                return null
            }
            val url = StringBuffer()
            var isfist = true
            for ((key, value) in paramToMap) {
                if (isfist) {
                    isfist = false
                } else {
                    url.append("&")
                }
                url.append(key).append("=")
                if (!TextUtils.isEmpty(value)) {
                    try {
                        url.append(URLEncoder.encode(value, "UTF-8"))
                    } catch (e: UnsupportedEncodingException) {
                        e.printStackTrace()
                    }
                }
            }
            return url.toString()
        }
    }
}

get请求

…… 
// 设置为get
httpURLConnection.setRequestMethod("GET");
// 把上边的out换成in
InputStream inputStream = httpURLConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            final StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
  把sb回掉出去          
 ……            

调用

		// json请求则是把params改为JSONObject 直接传输
		val params: MutableMap<String, String> = HashMap()
        params["z"] = z
        params["a"] =a
        params["b"] = b
        AsyncTaskUtils.map2Url(params)?.let {
            AsyncTaskUtils(it, object : NetCallback {
                override fun onSuccess(response: String?) {
                }

                override fun onFailure() {
                }
            }).execute()
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值