Skip to content

Instantly share code, notes, and snippets.

@mashingan
Last active January 10, 2018 19:05
Show Gist options
  • Save mashingan/45209b51daef2df96ce88e0b782b6cbd to your computer and use it in GitHub Desktop.
Save mashingan/45209b51daef2df96ce88e0b782b6cbd to your computer and use it in GitHub Desktop.
package io.mashingan.getfetching
/*
Compile like from console:
$ kotlinc jsonfetcher.kt -include-runtime -d jsonf.jar
$ java -jar jsonf.jar
*/
//import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.SSLSocket
//import java.util.concurrent.TimeUnit
fun request(method: String, path: String,
headers: Map<String, String>? = null): String? {
val conn = when(path.startsWith("https")) {
true -> URL(path).openConnection() as HttpsURLConnection
false -> URL(path).openConnection() as HttpURLConnection
}
return with(conn) {
requestMethod = method
headers?.forEach { (k, v) -> setRequestProperty(k, v)}
connect()
val streamed = when(responseCode != HttpURLConnection.HTTP_OK) {
true -> errorStream
false -> inputStream
}
val stream = streamed?.bufferedReader()
val result = buildString {
while(true) {
val line = stream?.readLine()
line ?: break
append(line)
}
}
disconnect()
result
}
}
fun main(args: Array<String>) {
val url = "myawesome.url"
// some piece of code that check supported cipher suites
if (url.startsWith("https")) {
val sock = HttpsURLConnection
.getDefaultSSLSocketFactory()
.createSocket() as SSLSocket
val enabledCiphers: Array<String> = sock.getEnabledCipherSuites()
enabledCiphers.forEach { println("$it") }
}
val starttime = System.nanoTime()
val reqdata = request("GET", url)
val lapsed = System.nanoTime() - starttime
println("reqdata: $reqdata")
println("elapsed time in ${lapsed / 1000000} milliseconds")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment