2017-03-03 268 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”);