使用HttpClient获取网页html源代码的Android例子源码

在Android开发中,我们经常需要从网络上获取数据,而获取网页的html源代码是其中比较常见的一种需求。本文将介绍如何使用HttpClient获取网页的html源代码。

首先,我们需要在Android应用程序中添加HttpClient库的依赖。在build.gradle文件中添加以下代码:

```

dependencies {

implementation 'org.apache.httpcomponents:httpclient:4.5.12'

}

```

接着,我们就可以使用HttpClient来获取网页的html源代码了。下面是一个示例代码:

```

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;

public class MainActivity extends AppCompatActivity {

private TextView textView;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

textView = findViewById(R.id.text_view);

new Thread(new Runnable() {

@Override

public void run() {

try {

HttpClient httpClient = new DefaultHttpClient();

HttpGet httpGet = new HttpGet("http://www.baidu.com");

HttpResponse httpResponse = httpClient.execute(httpGet);

if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){

//获取网页的html源代码

String html = EntityUtils.toString(httpResponse.getEntity());

//更新UI

runOnUiThread(new Runnable() {

@Override

public void run() {

textView.setText(html);

}

});

}

} catch (IOException e) {

e.printStackTrace();

}

}

}).start();

}

}

```

以上代码中,我们先创建了一个HttpClient对象和一个HttpGet对象,然后执行HttpGet请求并获取HttpResponse对象。如果HttpResponse的状态码为200,说明请求成功,我们就可以使用EntityUtils将HttpResponse的实体转换为字符串,从而获取网页的html源代码。最后,我们在主线程中更新UI,将获取到的html源代码显示在TextView中。

需要注意的是,HttpClient已经被官方废弃,推荐使用HttpUrlConnection或OkHttp来替代。以上示例代码仅供参考,实际开发中应该使用更加安全、稳定的网络请求方式。