The network requests a mobile phone number, and the result returns null, because the function executes return without waiting for the network request to come back. How to modify the following code?
public String getPhone(String id) {
String url = "http://www.163.net/";
final String[] phone = new String[1];
OkHttpUtils
.get()
.url(url)
.addParams("username", "abc")
.addParams("password", "123")
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
}
@Override
public void onResponse(String response, int id) {
phone[0] = response;
}
});
return phone[0];
}
Of course you need to use CountDownLatch to convert asynchronous requests into blocking synchronous requests
I think there is something wrong with your function. The formal parameter id is not used in it, which is very strange. If you want to obtain asynchronous data, the most commonly used one is asynchronous callback. You can try RXJava in the future and you will be surprised.
Rewrite this function as follows:
When calling, it can be