android学习连接网页

来源:互联网 发布:淘宝口碑好的大码女装 编辑:程序博客网 时间:2024/06/06 16:53
public class HttpStudyConnect {public String httpClient(String url) {String str = null;InputStream input = null;BufferedReader reader = null;try {// 取得默认的HttpClientHttpClient httpClient = new DefaultHttpClient();// HttpGet连接对象HttpGet httpGet = new HttpGet(url);// 取得HttpResponse,发起GET请求HttpResponse response = httpClient.execute(httpGet);// 获取服务器响应内容// str = EntityUtils.toString(response.getEntity());// Log.i("11", "返回的状态码>>>:" + str);// HttpStatus.SC_OK表示连接成功,获取响应码int n = response.getStatusLine().getStatusCode();Log.i("11", "返回的状态码>>>:" + n);if (n == HttpStatus.SC_OK) {input = response.getEntity().getContent();reader = new BufferedReader(new InputStreamReader(input,HTTP.UTF_8));//创建StringBuilder对象用于存储所有数据 StringBuilder builder = new StringBuilder();String line = null;while ((line = reader.readLine()) != null) {builder.append(line);}return builder.toString();}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (input != null) {input.close();input = null;}if (reader != null) {reader.close();reader = null;}} catch (IOException e) {e.printStackTrace();}}return str;}}

在Activity界面里面的调用:

public class HttpActivity extends Activity implements OnItemClickListener {private ListView httpStudyList;private WebView httpStudyWebView;String urls = "http://www.baidu.com";// String urls = "http://192.168.1.191:8080/Html/wanmei.html";HttpStudyConnect mHttpStudyConnect;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.http_study_layout);mHttpStudyConnect = new HttpStudyConnect();String[] s = { "httpClient连接1", "JAVA_连接2" };httpStudyList = (ListView) findViewById(R.id.http_study_listview);httpStudyWebView = (WebView) findViewById(R.id.http_study_webview);ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1, s);httpStudyList.setAdapter(adapter);httpStudyList.setOnItemClickListener(this);}

封装了一个检查网络是否可用的方法:

/** * 检查网络是否可用 */public boolean inspectMesh() {ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);Log.i("11","11111");NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();Log.i("11","2222");if (networkInfo != null && networkInfo.isConnected()) {return true;}return false;}

监听事件的处理,并用了Aysnctask异步处理数据:

public void onItemClick(AdapterView<?> parent, View view, int position,long id) {boolean temp = inspectMesh();switch (position) {case 0:if(temp == true){Log.i("11", "111345634");// 主线程中去处理异步任务new AsyncTask<String, Void, String>() {//String...:说明这是一个可变的数组,长度不确定protected String doInBackground(String... params) {//此处取数据时根据你下面传递参数的时候,你放的第几个位置,execute("s1","s2","s3")String toHttp = params[0];String contentUrl = mHttpStudyConnect.httpClient(toHttp);return contentUrl;}//接收doInBackground返回的参数protected void onPostExecute(String result) {super.onPostExecute(result);if (result != null) {httpStudyWebView.loadData(result, "text/html;utf-8",null);}}}.execute(urls);}else{Toast.makeText(HttpActivity.this, "网络连接不可用", 0).show();}break;


AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,
并提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI主线程:

/** *  * 三种泛型类型分别代表“启动任务执行的输入参数”、“后台任务执行的进度”、“后台计算结果的类型”。 在特定场合下, * 并不是所有类型都被使用,如果没有被使用,可以用java.lang.Void类型代替。 * */public class MyAsyncTask extends AsyncTask<String, Integer, String> {protected String doInBackground(String... params) {String httpurl = params[0];String str = null;// HttpPost连接对象try {HttpPost httpRequest = new HttpPost(httpurl);// 设置参数List<NameValuePair> param = new ArrayList<NameValuePair>();param.add(new BasicNameValuePair("one", ""));param.add(new BasicNameValuePair("options", "dododo"));param.add(new BasicNameValuePair("two", ""));// 设置字符集,以及编码方式HttpEntity httpEntity = new UrlEncodedFormEntity(param, "utf-8");// 请求HttpRequesthttpRequest.setEntity(httpEntity);// 取得默认的HttpClientHttpClient httpClient = new DefaultHttpClient();// 取得HttpResponseHttpResponse httpResponse = httpClient.execute(httpRequest);str = EntityUtils.toString(httpResponse.getEntity());// HttpStatus.SC_OK表示连接成功Log.v("gzg", "" + httpResponse.getStatusLine().getStatusCode());} catch (Exception ex) {ex.printStackTrace();}return str;}protected void onPostExecute(String result) {// ((TextView) findViewById(R.id.a)).setText("异步操作执行结束"+result);// //异步操作执行完后,在TextView中显示出来,也可以执行别的操作。};protected void onProgressUpdate(Integer... values) {};}



 




 

0 0