網路要求一個手機號,結果回傳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
}
});