向服务器发出一个简单请求,给我不同的响应数据。 Volley
和HttpURLConnection
给出了与我预期相同的响应,但是,当我请求使用翻新时,它给了我完全不同的数据。
请记住,只有当我使用我们的 WIFI 且仅在移动应用程序中时,这种情况才会发生。当我使用浏览器并发出相同的请求时,我得到了预期的数据。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val alarmManger = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, AlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)
alarmManger.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
60 * 1000, pendingIntent)
Thread {
var conn = URL("$BASE_URL/home").openConnection() as HttpURLConnection
var inputStream = conn.inputStream
val br = BufferedReader(InputStreamReader(inputStream))
var sB = StringBuilder()
var line = br.readLine();
if (line != null) {
sB.append(line)
}
print(sB.toString())
}.start()
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.build()
val service = retrofit.create(GitHubService::class.java)
service.listRepos().enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
println(t)
}
override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
println(response?.body())
}
})
val queue = Volley.newRequestQueue(this)
val stringRequest = StringRequest(Request.Method.GET, BASE_URL + "/home",
com.android.volley.Response.Listener<String> { response ->
println(response)
},
com.android.volley.Response.ErrorListener { })
queue.add(stringRequest)
}
}
val BASE_URL = "myserviceurl";
interface GitHubService {
@GET("home")
fun listRepos(): Call<ResponseBody>
}