【发布时间】:2018-01-23 22:36:24
【问题描述】:
我正在尝试从这个 URL https://fantasy.premierleague.com/drf/elements 解析 JSON,但我从 okhttp 和 Postman 得到的响应是不同的。我还使用了在线 API 测试器,并且在那里我得到了完整的 JSON 响应。我不确定为什么我的代码不起作用。
谁能帮我解决这个问题?
这是我用于快速测试的代码。
val request = Request.Builder()
.url("https://fantasy.premierleague.com/drf/elements")
.get()
.addHeader("accept", "*/*")
.addHeader("accept-encoding", "gzip, deflate")
.addHeader("cache-control", "no-cache")
.addHeader("connection", "keep-alive")
.cacheControl(CacheControl.FORCE_NETWORK)
.build()
val httpClient = OkHttpClient()
httpClient.newCall(request).enqueue(object : okhttp3.Callback {
override fun onFailure(call: okhttp3.Call?, e: IOException?) {
Timber.d("FPL response failed = " + e?.message.toString())
}
override fun onResponse(call: okhttp3.Call?, response: okhttp3.Response?) {
if (response!!.isSuccessful) {
val responseBody = response.body()?.string()
try {
val obj = JSONObject(responseBody)
Timber.d("FPL response = " + obj.toString())
} catch (t: Throwable) {
Timber.e("Could not parse malformed JSON: " + t.message)
}
Timber.d("FPL response = $response")
Timber.d("FPL headers = " + response.headers())
Timber.d("FPL body = " + responseBody)
} else {
Timber.d("FPL response failed = " + response.body().toString())
}
}
})
我尝试复制 Postman 的代码 sn-p 标头,它们是:
Request request = new Request.Builder()
.url("https://fantasy.premierleague.com/drf/elements")
.get()
.addHeader("cache-control", "no-cache")
.addHeader("postman-token", "05ae03ef-cf44-618c-a82c-5762e245b771")
.build();
但遗憾的是那里也没有运气。
日志:
D/HomeController$onAttach:L135: FPL response = Response{protocol=http/1.1, code=200, message=OK, url=https://fantasy.premierleague.com/drf/elements}
D/HomeController$onAttach:L138: FPL headers =
Server: Varnish
Retry-After: 0
Content-Type: application/json
Content-Length: 0
Accept-Ranges: bytes
Date: Tue, 15 Aug 2017 22:17:18 GMT
Via: 1.1 varnish
Connection: close
X-Served-By: cache-jfk8123-JFK
X-Cache: MISS
X-Cache-Hits: 0
X-Timer: S1502835438.419014,VS0,VE0
D/HomeController$onAttach:L139: FPL body =
如您所见,主体为空,“连接”已关闭。
这是 Postman 获得的响应标头,大不相同。
Accept-Ranges →bytes
Age →14
Allow →GET, HEAD, OPTIONS
Cache-Control →no-cache, no-store, must-revalidate, max-age=0
Connection →keep-alive
Content-Encoding →gzip
Content-Language →plfplen
Content-Length →39518
Content-Type →application/json
Date →Tue, 15 Aug 2017 00:54:32 GMT
Edge-Control →max-age=60
Fastly-Debug-Digest →fdb44d2dd7c0b26c639a8b3476f8c63661c68707cc3b9446f8ed3941cd3fe01e
Server →nginx
Vary →Accept-Encoding
Via →1.1 varnish
Via →1.1 varnish
X-Cache →HIT, MISS
X-Cache-Hits →1, 0
X-Frame-Options →DENY
X-Served-By →cache-lcy1146-LCY, cache-jfk8143-JFK
X-Timer →S1502758472.116470,VS0,VE82
如您所见,“连接”表示保持活动状态。
我的 Request.Builder() 中是否缺少某些东西以使其正常工作?
编辑:
因此,我决定尝试使用AsyncTask 发出请求,并返回完整的 JSON,如下面的日志所示。我不明白为什么Okhttp3 不起作用。
val url = params[0]
var stream: InputStream? = null
var connection: HttpsURLConnection? = null
var result: String? = null
try {
connection = url?.openConnection() as HttpsURLConnection?
// Timeout for reading InputStream arbitrarily set to 3000ms.
connection?.readTimeout = 3000
// Timeout for connection.connect() arbitrarily set to 3000ms.
connection?.connectTimeout = 3000
// For this use case, set HTTP method to GET.
connection?.requestMethod = "GET"
// Already true by default but setting just in case; needs to be true since this request
// is carrying an input (response) body.
connection?.doInput = true
// Open communications link (network traffic occurs here).
connection?.connect()
val responseCode = connection?.responseCode
if (responseCode != HttpsURLConnection.HTTP_OK) {
throw IOException("HTTP error code: " + responseCode)
}
// Retrieve the response body as an InputStream.
stream = connection?.inputStream
Timber.d("httpurl stream = " + connection?.inputStream.toString())
if (stream != null) {
// Converts Stream to String with max length of 500.
result = readStream(stream, 500)
}
} finally {
// Close Stream and disconnect HTTPS connection.
if (stream != null) {
stream.close()
}
if (connection != null) {
connection.disconnect()
}
}
return result
日志:
D/HomeController$NetworkA:L266: httpurl response = [{"id":1,"photo":"48844.jpg","web_name":"Ospina","team_code":3,"status":"a","code":48844,"first_name":"David","second_name":"Ospina","squad_number":13,"news":"","now_cost":50, .... }]
【问题讨论】:
-
该 URL 使用 301 重定向。尝试在末尾添加斜杠 (
https://fantasy.premierleague.com/drf/elements/) 以访问重定向的 URL。 OkHttp 应该自动跟随重定向,所以这可能无济于事。但是,使用curl(不遵循重定向)进行测试,我得到的结果与使用原始 URL 对 OkHttp 所做的结果相同,如果我在末尾添加/,我会得到 JSON 响应。 -
@CommonsWare 好的,刚刚尝试将
/添加到末尾,但仍然没有成功。我也尝试了curl的url,它确实返回了响应。我不确定为什么使用 Okhttp3 不起作用。 -
@CommonsWare 查看我的编辑,我刚刚使用
AsyncTask、HttpsURLConnection和InputStreamReader的老式方式发出了相同的请求,我得到了完整的 JSON。Okhttp3不起作用真的很奇怪。 -
可能值得组合一个可重现的测试用例并将其作为问题发布。如果 HURL 可以处理,OkHttp 应该。
-
一种帮助调试的方法是添加一个记录 HTTP 请求的 NetworkInterceptor,这样您就可以深入了解实际发生的情况。这是一个配置OkHttpClient logging interceptor 的可运行示例,这将为您提供更好的调试日志记录以及第一个请求和最终响应之间的所有网络跃点。您可能可以使用 Timber 日志记录而不是 SLF4J
标签: android kotlin postman okhttp3