[英]Async POST request in Java for Android
public void btnWeb_Click(View view){
String url="http://localhost/test/index.php";
List<NameValuePair> dict = new ArrayList<NameValuePair>();
dict.add(new BasicNameValuePair("url",url));
dict.add(new BasicNameValuePair("id", "3"));
PostReq postreq= new PostReq();
postreq.execute(dict);
String result="";
while(result==""){ result= postreq.content;}
System.out.println(result); }
PostReq
是异步执行对服务器的Post请求的类。
问题是,如果我不放置while
,则打印函数会将变量RESULT打印为空,因为它没有等待线程postreq.execute(dict)
完成操作。
我用WHILE
强制等待,但是WHILE
阻塞了主线程。
如何等待方法执行完毕,然后异步将值分配给变量RESULT
?
例如,在Windows Phone的C#中,我是这样进行的:
async void button_click() {
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("id", "3");
string url="http://localhost/test/index.php";
PostReq pr= new PostReq(url,dict);
String risposta = await pr.getRisposta(); }
改用Java for Android我该怎么办?
看一下AsyncTask。 在while循环中重复检查结果是否另一个线程的结果不是一个好主意。
http://developer.android.com/reference/android/os/AsyncTask.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.