在我的代码中出现错误500,但在浏览器中却没有

时间:2019-12-16 16:33:03

标签: android kotlin

我正在尝试通过此代码使用theDuckDuck go api

val mainVal = searchQuery.replace(" ", "+")
    val url = URL("https://api.duckduckgo.com/?q=$mainVal&format=json")
    println(url.host)
    url.openConnection()
    val json = url.readText()

我收到此错误

java.io.IOException: Server returned HTTP response code: 500 for URL: https://api.duckduckgo.com/?q=duck+duck+go&format=json
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
at java.base/java.net.URL.openStream(URL.java:1139)
at kotlin.io.TextStreamsKt.readBytes(ReadWrite.kt:150)
at com.andromeda.araserver.skills.GetInfo.getFast(GetInfo.kt:82)
at com.andromeda.araserver.skills.GetInfo.searchBing(GetInfo.kt:43)
at com.andromeda.araserver.skills.GetInfo.main(GetInfo.kt:28)
at com.andromeda.araserver.Run.serve(Run.java:98)
at fi.iki.elonen.NanoHTTPD$HTTPSession.execute(NanoHTTPD.java:945)
at fi.iki.elonen.NanoHTTPD$ClientHandler.run(NanoHTTPD.java:192)
at java.base/java.lang.Thread.run(Thread.java:834)

当我在浏览器中运行给定链接时,它将返回预期结果。我尝试使用HttpSConnection方法,但没有用。

请注意,我在https上已经多次使用这种方法,这不是问题。

1 个答案:

答案 0 :(得分:0)

确保在清单中添加了 INTERNET 权限

使用 Uri.encode 方法对URL进行编码,而不是添加“ +”:

//        val mainVal = searchQuery.replace(" ", "+")

            val mainVal = Uri.encode(searchQuery)

            val url = URL("https://api.duckduckgo.com/?q=$mainVal&format=json")
            println(url.host)
            url.openConnection()
            val json = url.readText()
            println("Result = " + json)