2015-07-10 81 views
1

我想從網址獲取源代碼。但我發現的所有東西都被棄用,或者它不是我想要的,所以我仍然在尋找,但我什麼也沒找到。在Android中,如何將HTML源代碼轉換爲字符串?

推薦使用:

HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client 
HttpGet httpget = new HttpGet("http://yoururl.com"); // Set the action you want to do 
HttpResponse response = httpclient.execute(httpget); // Executeit 
HttpEntity entity = response.getEntity(); 
InputStream is = entity.getContent(); // Create an InputStream with the response 
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
StringBuilder sb = new StringBuilder(); 
String line = null; 
while ((line = reader.readLine()) != null) // Read line by line 
    sb.append(line + "\n"); 

String resString = sb.toString(); // Result is here 

is.close(); // Close the stream 

你能幫助我嗎?使用HttpClient的距離的Apache HTTP

回答

0

嘗試

class Task extends AsyncTask<Void, Void, String> { 

      @Override 
      protected String doInBackground(Void... params) { 
       try { 
        HttpPost httppost = new HttpPost("https://www.google.com"); 
        httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpResponse httpresponse = httpclient.execute(httppost); 
        HttpEntity resEntity = httpresponse.getEntity(); 
        String str = EntityUtils.toString(resEntity); 
        return str; 
       } catch (Exception ex) { 
        return ex.getMessage(); 
       } 
      } 

      Listener listen; 
      @Override 
      protected void onPostExecute(String result) { 
       listen.returnVal(result); 
      } 

     } 

    public interface Listener { 
     public void returnVal(String str); 
    } 

public class Activity1 extends ActionBarActivity implements Listener { 
... 

protected void onCreate(Bundle savedInstanceState) { 
.... 
Task t = new Task(); 
     t.listen = this; 
     t.execute(); 
} 

@Override 
    public void returnVal(String str) { 
     // Http Response 
    } 

不要忘了在你的manfiest

+0

你是什麼意思與soapAction?我沒有這個,所有的功能都被棄用了。 –

+0

好的,謝謝,小心你將「HttpResponse」粘貼到變量上:) –

+0

謝謝,請嘗試告訴我。 –

1

使用替代HTTP客戶端添加<uses-permission android:name="android.permission.INTERNET"/>這將是更快,更好。我可以推薦你這個。

https://square.github.io/okhttp/

+0

謝謝,我會嘗試。 –

+0

不客氣 –

相關問題