问题描述
网络请求一个手机号,结果返回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() {@Overridepublic void onError(Call call, Exception e, int id) {}@Overridepublic void onResponse(String response, int id) { phone[0] = response;} }); return phone[0];}
问题解答
回答1:当然要用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() {@Overridepublic void onError(Call call, Exception e, int id) { latch.countDown(); }@Overridepublic void onResponse(String response, int id) { phone[0] = response; latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { } return phone[0];}回答2:
我觉得你这个函数有问题啊,那个形参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(){@Overridepublic void onError(Call call, Exception e, int id) { //do something}@Overridepublic void onResponse(String response, int id) { //do something}});