Сбой, когда OkHttp запрашивает неверные ссылки - PullRequest
0 голосов
/ 17 января 2019

Когда я попросил ссылку с помощью OKHttp, она упала, потому что это была неправильная ссылка, как мне зафиксировать сбой, и я не уверен, будут ли какие-либо из этих неправильных ссылок в будущем. Мне нужно захватить его, чтобы избежать сбоев программы

Эта статья создается с помощью инструментов перевода, если вы не понимаете, пожалуйста, дайте мне знать.

try {
     val request = Request.Builder()
         .url("http://pic1.nipic.com|/2008-12-30/200812308231244_2.jpg ")
         .build()
     val client = OkHttpClient
         .Builder()
         .build()

     client.newCall(request).enqueue(object : Callback {

            override fun onResponse(call: Call, response: Response) {
                val s = response.body().toString()
                println(s)
            }

            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
            }
        })
    } catch (e: Exception) {
    }

Хотелось бы мне запечатлеть это и избежать крушения.

java.lang.RuntimeException: java.net.URISyntaxException: Illegal character in authority at index 21: http://pic1.nipic.com|/
    at okhttp3.HttpUrl.uri(HttpUrl.java:386)
    at okhttp3.internal.connection.RouteSelector.resetNextProxy(RouteSelector.java:129)
    at okhttp3.internal.connection.RouteSelector.<init>(RouteSelector.java:63)
    at okhttp3.internal.connection.StreamAllocation.<init>(StreamAllocation.java:101)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:112)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
    at okhttp3.RealCall$AsyncCall.execute(RealCall.java:200)
    at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
    at java.lang.Thread.run(Thread.java:818)
 Caused by: java.net.URISyntaxException: Illegal character in authority at index 21: http://pic1.nipic.com|/
    at libcore.net.UriCodec.validate(UriCodec.java:63)
    at java.net.URI.parseURI(URI.java:395)
    at java.net.URI.<init>(URI.java:205)
    at okhttp3.HttpUrl.uri(HttpUrl.java:379)
    at okhttp3.internal.connection.RouteSelector.resetNextProxy(RouteSelector.java:129) 
    at okhttp3.internal.connection.RouteSelector.<init>(RouteSelector.java:63) 
    at okhttp3.internal.connection.StreamAllocation.<init>(StreamAllocation.java:101) 
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:112) 
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) 
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254) 
    at okhttp3.RealCall$AsyncCall.execute(RealCall.java:200) 
    at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
    at java.lang.Thread.run(Thread.java:818) 

Ответы [ 2 ]

0 голосов
/ 22 января 2019

Как правило, вы можете избежать исключения, используя try catch block

    private fun testing() {
        val request = Request.Builder()
        try {
            val httpUrl = HttpUrl.parse("http://pic1.nipic.com|/2008-12-30/200812308231244_2.jpg")?.uri()
            httpUrl?.let {
                request.url(it.toURL())
            }
        }catch (e: Exception) {
            Log.d("Testing", e.toString())
            return
        }


        val client = OkHttpClient.Builder().build()

        client.newCall(request.build()).enqueue(object: Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.d("Testing", e.toString())
            }

            override fun onResponse(call: Call, response: Response) {
                Log.d("Testing", response.body().toString())
            }
        })
    }
}

См. Ссылку ниже для получения дополнительной информации https://github.com/square/okhttp/issues/543

0 голосов
/ 22 января 2019

Ну, это потому, что вы передали специальный символ в URL, который делает его поврежденным. Чтобы избежать сбоя, вы можете просто удалить специальные символы из ссылки перед выполнением кода:

url = url.replaceAll("[|?*<\":>+\\[\\]/']", "");
...