[英]asynchronous GET request method receives data but return null array, works fine while debugging
MainActivity.java MainActivity.java
String[] captcha = new String[2];
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getMessle();
}
});
private void getMessle() {
captcha[0] = "before";
captcha[1] = "before2";
RequestClass rc = new RequestClass();
captcha = rc.getCaptcha();
tv.setText(captcha[1]);
}
RequestClass.java RequestClass.java
String[] saResult = new String[2];
public String[] getCaptcha() {
httpUrl = new HttpUrl.Builder()
.scheme(strScheme)
.host(strHost)
.addPathSegments(path)
.build();
request = new Request.Builder()
.url(httpUrl)
.addHeader(header, key)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
saResult[0] = response.header("Set-Cookie");
try {
jsonObject = new JSONObject(response.body().string());
saResult[1] = jsonObject.getString("image_url");
} catch (JSONException je) {
}
}
});
return saResult;
}
I've checked and it doesn't seem like any exceptions are caught. 我检查了一下,似乎没有发现任何异常。 I also know that my application gets a response as well and the datas are definitely there in onResponse().
我也知道我的应用程序也能收到响应,并且数据肯定在onResponse()中。 After some extended testing, it looks like my array is assigned before the response arrives.
经过一些扩展的测试后,似乎在响应到达之前就分配了我的数组。
captcha = rc.getCaptcha();
验证码= rc.getCaptcha();
You call that right after you enqued a request. 您在收到请求后立即致电。 The request is not executed then nor is there a result.
然后不执行该请求,也没有结果。 All goes asynchronous.
一切都是异步的。
Only in onResponse() you will get the result. 仅在onResponse()中,您将获得结果。 A long time later.
很久以后。 And it is in onResponse() that you should handle the result by displaying it in a text view for instance.
在onResponse()中,您应该通过例如在文本视图中显示结果来处理结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.