Kotlin在處理GET和POST請求的數據問題


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/pngpng圖片格式
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 <form encType=””>中默認的encTypeform表單數據被編碼為key/value格式發送到服務器(表單默認的提交數據的格式)

另外一種常見的媒體格式是上傳文件之時使用的:
multipart/form-data : 需要在表單中進行文件上傳時,就需要使用該格式
注意:MediaType.parse("image/png")里的"image/png"不知道該填什么,可以參考---http://www.w3school.com.cn/media/media_mimeref.asp
如何使用呢?(在請求體里面寫入類型和需要寫入的數據,通過post請求)
*/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM