Volley、ngrok - 无法使用Volley向ngrok REST API发出post请求

3

我一直在为许多项目使用ngrok,主要是语音应用程序和rest api。我只需要在Android应用程序中使用我的rest api。但是,无论我做什么,出于某些原因都无法正常工作!

如果我尝试使用http,将会得到以下错误:

E/Volley: [17118] BasicNetwork.performRequest: Unexpected response code 307 for http://1z5d90b4.ngrok.io/api/v1/users/id/
I/System.out: That didn't work! com.android.volley.ServerError 

如果我尝试使用https链接,得到的结果如下:

com.android.volley.NoConnectionError: javax.net.ssl.SSLHandshakeException: SSL handshake aborted: ssl=0xd7821100: I/O error during system call, Connection reset by peer

我不知道发生了什么!我检查了在我的电脑上运行的ngrok,但是它没有接收到任何信息。提供信息,我正在使用Kotlin中的Volley在该URL上进行post请求,这是我的代码:

        val queue = Volley.newRequestQueue(this)

    // Request a string response from the provided URL.
        val stringRequest = JsonObjectRequest(Request.Method.POST, apiUrl, params,
                Response.Listener { response ->
                    // Display the first 500 characters of the response string.
                    println("Response is: $response")
                },
                Response.ErrorListener { error ->  println("That didn't work! ${error}") })
        queue.add(stringRequest)


你正在尝试访问的URL http://1z5d90b4.ngrok.io/api/v1/users/id/ 看起来不正确。它可能是正确的,但奇怪的是没有最终的URL参数,例如用户ID? - Cody Caughlan
实际上,我删掉了URL,因为我认为它不是必要的。但它类似于这样:当我使用Postman发出请求时,它可以正常工作。 - Mark
你的URL是http,但错误与SSL有关,这似乎很奇怪...? - Cody Caughlan
@CodyCaughlan 感谢您抽出时间检查代码并回复。我找到问题所在了!原来是网络防火墙的问题!我没有想到这一点,因为我们在工作中有一个访客网络和一个工作网络。我的假设是,由于工作网络更安全,如果在工作网络上运行正常,那么在访客网络上也会正常运行!然而,ngrok在访客网络上被阻止了,这就是唯一的问题。 - Mark
1个回答

2
我找到问题所在了!听起来很傻,但是它是由于网络防火墙引起的!一旦我更改了网络,一切都解决了!
补充一点,如果你遇到了HTTP请求的问题,请尝试在AndroidManifest.xml文件中添加android:usesCleartextTraffic="true"。它将类似于以下内容:
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>

    <!--Add this line if you haven't added it yet-->
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        ...

       <!--ALSO, this can fix some of the problems-->
        android:usesCleartextTraffic="true"


        ...>
        ...
    </application>
</manifest>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接