2014-07-18 49 views
-3

好吧,所以我的HttpClient調用不工作在java android我試圖用try和catch來包圍它,並且它保持失敗。請幫忙!!!android java Httpclient連接

 BufferedReader in = null; 

    try { 
     HttpClient client = new DefaultHttpClient(); 
     URI ur = new URI("http://192.168.1.10/test/randomy/generate/index.php"); 
     HttpGet request = new HttpGet(); 
     request.setURI(ur); 
     HttpResponse response = client.execute(request); 
     in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
     String l = ""; 
     StringBuffer sb = new StringBuffer("test"); 
     while((l=in.readLine())!=null){ 

      sb.append(l); 

     } 
     in.close(); 
     return sb.toString(); 

    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     if(in!=null){ 

      try { 
       in.close(); 
      } catch (IOException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 

     } 
     return "Error"; 
    } 
+5

你得到什麼錯誤?您是否在清單文件中添加了互聯網許可? – GrIsHu

+0

是的,我做到了。但你如何閱讀錯誤? – Sam

+0

是在瀏覽器中工作的鏈接。當您在瀏覽器中點擊該鏈接時,您是否嘗試獲得響應> – VVB

回答

0

網絡操作應該分開進行。你可以使用AsyncTask

new Thread(){ 

public void run() { 
//your code 
} 
}; 

環繞,你也可以通過onCreate方法使用

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

禁用錯誤。

+0

謝謝你們的幫助 – Sam

1

使用本& &閱讀本Tutorial

class testAsynk extends AsyncTask<Void, Integer, String> 
{ 
    protected void onPreExecute(){ 
     Log.d("PreExceute","On pre Exceute......"); 
    } 

    protected String doInBackground(Void...arg0) { 
     Log.d("DoINBackGround","On doInBackground..."); 
//Send the Http Request 
     for(int i=0; i<10; i++){ 
      Integer in = new Integer(i); 
      publishProgress(i); 
     } 
     return "You are at PostExecute"; 
    } 

    protected void onProgressUpdate(Integer...a){ 
     Log.d("You are in progress update ... " + a[0]); 
    } 

    protected void onPostExecute(String result) { 
     Log.d(""+result); 
    } 
} 

**調用從活動**

new testAsynk().execute(); 
相關問題