网络请求一个手机号,结果返回null,因为函数没有等到网络请求回来就执行了return,请问下面的代码如何修改?
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];
}
黄舟2017-06-26 10:51:53
当然要用CountDownLatch 啦,异步请求转阻塞式同步请求
public String getPhone(String id) {
String url = "http://www.163.net/";
final CountDownLatch latch = new CountDownLatch(1);
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) {
latch.countDown();
}
@Override
public void onResponse(String response, int id) {
phone[0] = response;
latch.countDown();
}
});
try {
latch.await();
} catch (InterruptedException e) {
}
return phone[0];
}
世界只因有你2017-06-26 10:51:53
我觉得你这个函数有问题啊,那个形参id在里面没用到啊,很奇怪。假如想要获取异步的数据,最常用的的就是异步回调,你以后可以试下RXJava,会发现惊喜。
把这个函数改写下,如下:
public static void getPhone(String id,StringCallback cb) {
String url = "http://www.163.net/";
final String[] phone = new String[1];
OkHttpUtils
.get()
.url(url)
.addParams("username", "abc")
.addParams("password", "123")
.build()
.execute(cb);
}
在调用的时候,可以是
XXutil.getPhone("1234566",new StringCallback(){
@Override
public void onError(Call call, Exception e, int id) {
//do something
}
@Override
public void onResponse(String response, int id) {
//do something
}
});