2017-03-03 84 views
0

我是第一個參與android/java的noob,我剛剛開始研究它。在Java中獲取網頁內容(類似於php的file_get_contents())

我一直在尋找互聯網和整天嘗試不同的東西,以瞭解如何將網頁的內容轉換爲java中的字符串(無需webview)。所有被發現的東西要麼被棄用,要麼就是我缺乏理解力,我一直在閱讀文檔和所有東西,但它只是讓我的頭腦轉動,即使這個任務似乎很簡單,只需要php一個函數:file_get_contents()

我能夠做到這一點使用不可見的WebView,但據我所知,這是不是要走的路,加上我也想能夠發佈的東西到網頁(雖然我也許可以通過在web視圖上執行一些JavaScript來實現這一點,但仍然看起來並不是這樣)。

可有人請給我如何得到一個網頁的內容轉換成字符串 和一個簡單的例子來發布內容到一個網頁一個簡單的例子(和檢索響應轉換成字符串)

如果可能的話有一些解釋,但如果我得到一個工作的例子,我可以找出它爲什麼有效。

+1

看看這個http://stackoverflow.com/questions/1485708/how-do-i-do-a-http-get-in-java –

+0

@YohannesGebremariam我不明白這個例外事情(這是什麼我用今天試過的多個「解決方案」運行)..我所做的就是複製該代碼,並從中創建一個新的java文件,然後在我的主文件中調用c.getHTML(「http:// www .google.com「)被放入一個textview,但當我不知道該android-studio迫使我試圖抓住東西,所以我這樣做,但它總是在結果(我知道這是因爲在抓住我再舉一個字符串到TextView的) – Henk

+0

請發表您的例外,你已經嘗試 –

回答

1

對於任何人都可能會遇到這個問題,我已經用下面的代碼解決了這個問題(這包括添加後的參數,如果你想/需要):

private class GetContents extends AsyncTask<String, Void, String> { 
     protected String doInBackground(String... p) { 
      String targetURL = p[0]; 
      String urlParameters = p[1]; 
     URL url; 
     HttpURLConnection connection = null; 
     try { 
      //Create connection 
      url = new URL(targetURL); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setRequestMethod("POST"); 
      connection.setRequestProperty("Content-Type", 
        "application/x-www-form-urlencoded"); 

      connection.setRequestProperty("Content-Length", "" + 
        Integer.toString(urlParameters.getBytes().length)); 
      connection.setRequestProperty("Content-Language", "en-US"); 

      connection.setUseCaches(false); 
      connection.setDoInput(true); 
      connection.setDoOutput(true); 

      //Send request 
      DataOutputStream wr = new DataOutputStream(
        connection.getOutputStream()); 
      wr.writeBytes(urlParameters); 
      wr.flush(); 
      wr.close(); 

      //Get Response 
      InputStream is = connection.getInputStream(); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
      String line; 
      StringBuffer response = new StringBuffer(); 
      while ((line = rd.readLine()) != null) { 
       response.append(line); 
       response.append('\r'); 
      } 
      rd.close(); 
      return response.toString(); 

     } catch (Exception e) { 

      e.printStackTrace(); 
      return null; 

     } finally { 

      if (connection != null) { 
       connection.disconnect(); 
      } 
     } 


     } 

     protected void onPostExecute(String result) { 
      // do something 
     } 
    } 

,然後用它喜歡新GetContents.execute(「http://example.com」,「a = b」);

相關問題