2012-08-30 28 views
-1

運行我寫它適用於Android 2.2 API的代碼,但它並沒有在Android 4.0安卓:HttpClient的不Android 4.0的API

String url = textUrl.getText().toString(); 
    HttpClient client = new DefaultHttpClient(); 
    HttpGet request = new HttpGet(url); 
    try 
    { 
     HttpResponse response = client.execute(request); 
     textResult.setText(HttpHelper.request(response)); 
    } 
    catch (Exception e) { 
     // TODO: handle exception 
     textResult.setText("Failed"); 
    } 
+1

你會得到什麼樣的錯誤? – fiddler

+0

它生成異常,我沒有得到從URL的迴應 –

+1

你的代碼在哪裏?如果在Activity的'onCreate()'中,然後使用'AsyncTask' .. – user370305

回答

1

互聯網通信工作必須在一個單獨的線程中運行。

使用AsyncTask來簡化這一點。

你可以閱讀更多關於線程的Android here

編輯:如果你真的想進入主線程在互聯網上,你可以允許它在onCreate()方法用下面的代碼:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build(); 
StrictMode.setThreadPolicy(policy); 

但是,我真的不會推薦這種方法。

0

我得到了同樣的問題。 解決方案非常簡單: 您必須使用AsyncTaks。要實現它們,你可以簡單地創建一個新類。 PE:

public class AsynkTaskRequest extends AsyncTask<String, Void, String> { 


    @Override 
    protected String doInBackground(String... params) { 
     String answer = null; 

     for (String request : params) { 
      //your code comes here 
     } 
    } 
} 

有關詳細信息只是搜索了一下,你會發現它( 「i've searched for you this time」)

編輯: 不要使用:

catch (Exception e) { 
    // TODO: handle exception 
    textResult.setText("Failed"); 
} 

做到像

catch (Exception e) { 
    //if you use logcat in eclipse  
    Log.e("Request Error", e.getMessage()); 
    //else 
    System.out.println(e.getMessage());  
} 
1

如果您打電話到URL m在android 2.x中的主線程,那麼它將完美運行。

但是您需要發送HonyCumb及其上層版本的調用工作線程的URL。

您可以使用AsyncTask