我有一个正在调用的方法,但是对于较新版本的 Android,它失败了。显然,这是由于缺少线程。我的方法是向我的服务器发送消息。这是代码(无线程)
public String sendMessage(String username, Editable message){
BufferedReader in = null;
String data = null;
try{
DefaultHttpClient client = new DefaultHttpClient();
URI website = new URI("http://abc.com/user_send.php?username="+username+"&message="+message);
HttpPost post_request = new HttpPost();
post_request.setURI(website);
HttpGet request = new HttpGet();
request.setURI(website);
//executing actual request
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l);
}
in.close();
data = sb.toString();
return data;
}catch (Exception e){
return "ERROR";
}
}
现在,只是想在它周围放一个线程:
public String sendMessage(String username, Editable message){
BufferedReader in = null;
String data = null;
Thread sendThread = new Thread(){
try{
DefaultHttpClient client = new DefaultHttpClient();
URI website = new URI("http://thenjtechguy.com/njit/gds/user_send.php?username="+username+"&message="+message);
HttpPost post_request = new HttpPost();
post_request.setURI(website);
HttpGet request = new HttpGet();
request.setURI(website);
//executing actual request
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) != null) {
sb.append(l);
}
in.close();
data = sb.toString();
return data;
}catch (Exception e){
return "ERROR";
}
} sendThread.start();
}
但这不起作用。我究竟做错了什么?另外,如果您发现我违反了 android 中有关 HttpClient 的任何基本规则,请告诉我。