1.网络请求获取到的数据流处理
java写法
1 BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8")); 2 3 String line; 4 StringBuffer sb = new StringBuffer(); 5 while ((line = br.readLine()) != null) {//cotlin会出现无限循环的语法错误 6 sb.append(line); 7 }
Kotlin改写连接字符的几种写法
写法一
var inStrem: InputStream = response.body().byteStream()
var br: BufferedReader = BufferedReader(InputStreamReader(inStrem, "utf-8"))
var line: String?=null
var sb: StringBuffer = StringBuffer()
while ({ line = br.readLine(); line }() != null) { // <--- The IDE asks me to replace this line for while(true), what the...?
sb.append(line)
}
写法二
1 while ({line = br.readLine();line}()!=null) { 2 sb.append(line) 3 }
写法三
br.lineSequence().forEach { print(it) sb.append(it) }
2.okhttp处理
public fun connectHttp(url: String) :String? { var tempString:String?=null var client: OkHttpClient = OkHttpClient() val requset = Request.Builder() .url(url) .post(RequestBody.create(MediaType.parse("text/plain; utf-8"), "this is test")) .build()
//异步处理 client.newCall(requset).enqueue(object : Callback { override fun onFailure(request: Request?, e: IOException?) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onResponse(response: Response?) { if (response!!.isSuccessful) tempString = response.body().string() TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }) if (tempString!!.isEmpty()){ return tempString }else return null }
数据体常见的请求属性:
/**
* 属性:
text/html : HTML格式
text/plain :纯文本格式
text/xml : XML格式
image/gif :gif图片格式
image/jpeg :jpg图片格式
image/png:png图片格式
以application开头的媒体格式类型:
application/xhtml+xml :XHTML格式
application/xml : XML数据格式
application/atom+xml :Atom XML聚合格式
application/json : JSON数据格式
application/pdf :pdf格式
application/msword : Word文档格式
application/octet-stream : 二进制流数据(如常见的文件下载)
application/x-www-form-urlencoded :