'why connection succese in jvm and fail with responseCode 400 in android project
I try this code in Idea and it work very well. but when I pack it as jar and import to another android porject, it fail. I am a green hand and don't know much. What is the different between them and how I can fix it?
fun getSourceCode(url: URL, encode: String = "UTF-8"): String {
var contentBuffer: StringBuffer? = StringBuffer()
val responseCode: Int
var con: HttpURLConnection? = null
try {
con = url.openConnection() as HttpURLConnection
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)")
con.connectTimeout = 60000
con.readTimeout = 60000
responseCode = con.responseCode
if (responseCode == -1) {
con.disconnect()
throw Exception("connect fail")
}
if (responseCode >= 400) {
con.disconnect()
throw Exception("connect fail, responseCode: $responseCode")
}
val inStr: InputStream = con.inputStream
val iStreamReader = InputStreamReader(inStr, encode)
val buffStr = BufferedReader(iStreamReader)
var str: String?
while (buffStr.readLine().also { str = it } != null) contentBuffer!!.append(str)
inStr.close()
} catch (e: IOException) {
e.printStackTrace()
contentBuffer = null
println("error: $url")
} finally {
con?.disconnect()
}
return contentBuffer.toString()
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
