2012-05-26 38 views
1

我想使用Android訪問參數化的URL。它所要做的就是「加載」頁面,以便它完成它應該做的事情(用給定的參數更新數據庫)。Android HttpClient只使用獲取請求將數據發送到服務器

我在加載url時遇到了麻煩,所以我在常規的HttpClient活動中觀看了視頻 - 只是等待響應並收集該信息。我認爲它仍然會加載頁面,因此也會讓頁面執行。我甚至無法正確運行頁面或收集響應。

這是我使用的代碼:

String url = "http://www.removed.com?param1="+param1+"&param2="+param2; 

     try{ 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpGet httpget = new HttpGet(url); 
      HttpResponse response = httpclient.execute(httpget); 
      HttpEntity entity = response.getEntity(); 
      InputStream webs = entity.getContent(); 
      try{ 
       BufferedReader reader = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"), 8); 
       test.setText(reader.readLine()); 
       webs.close(); 
      }catch(Exception e) { 
       Log.e("Error in conversion: ", e.toString()); 
      } 
     }catch(Exception e) { 
      Log.e("Error in connection: ", e.toString()); 
     } 

請讓我知道我能做些什麼來得到這個執行該頁面,並更新數據庫。如果我手動將參數放入瀏覽器中,它可以工作。

+0

當你運行上面的代碼時會發生什麼? –

回答

2

您還沒有發佈你運行這個或者是什麼錯誤,但浮現在腦海中的第一個兩件事情是:

  • 你有沒有在清單將Internet的權限?
  • 如果這是蜂窩,這是在單獨的線程中運行? - 從3.0開始,你不能在主顯示線程中運行HTTP請求。
+0

我剛剛添加了權限。之前,我收到了一個紅色的UnknownHostException,然後是我的URL。我仍然遇到錯誤,但現在是黑色。據我所知,這不是在一個單獨的線程。我所做的唯一的'新'是新的Intents。 –

+0

如果您編譯的是3.0或更高版本,它需要位於單獨的線程中。而UknownHostException意味着它找不到主機:) –

+0

我認爲我編譯的時間早於3.0,但我試圖在中途切換到4.0.3。不知道我是否成功。任何方式來檢查確定?我無法想象它爲什麼說它無法找到主機。我給它的網址正是它的名字。 –

0

在閱讀你在回答中的評論後,我想你正在尋找響應代碼。我在這裏發佈你的代碼,在我的代碼中工作得很好

String urlGET = "http://www.removed.com?param1="+param1+"&param2="+param2; 

HttpGet getMethod = new HttpGet(urlGET); 
    // if you are having some headers in your URL uncomment below line 
    //getMethod.addHeader("Content-Type", "application/form-data"); 
    HttpResponse response = null; 
    HttpClient httpClient = new DefaultHttpClient(); 
    try { 
     response = httpClient.execute(getMethod); 

     int responseCode = response.getStatusLine().getStatusCode(); 

     HttpEntity entity = response.getEntity(); 
     String responseBody = null; 

     if (entity != null) { 
      responseBody = EntityUtils.toString(entity); 
      //here you get response returned from your server 
      Log.e("response = ", responseBody); 

      // response.getEntity().consumeContent(); 

     } 
     JSONObject jsonObject = new JSONObject(responseBody); 
     // do whatever you want to do with your json reponse data 

     } 
     catch(Exception e) 
     { 
     e.printStackTrace(); 
     } 
相關問題