前言
为了测试,不想引入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()
}