使用clienthttp来进行网络访问
1.
首先是进行网络访问权限设置
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.exp.httpdemo"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="18" />
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name="com.exp.httpdemo.MainActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
- 1 package com.exp.httpdemo;
- 2
- 3 import java.io.InputStream;
- 4
- 5 import org.apache.http.HttpEntity;
- 6 import org.apache.http.HttpResponse;
- 7 import org.apache.http.client.HttpClient;
- 8 import org.apache.http.client.methods.HttpGet;
- 9 import org.apache.http.impl.client.DefaultHttpClient;
- 10 import org.apache.http.util.EntityUtils;
- 11
- 12 import android.os.Bundle;
- 13 import android.os.Handler;
- 14 import android.app.Activity;
- 15 import android.view.Menu;
- 16 import android.view.View;
- 17 import android.widget.TextView;
- 18
- 19 /**
- 20 * 使用HttpClient请求一个网页
- 21 *
- 22 */
- 23 public class MainActivity extends Activity {
- 24 TextView tvResult;
- 25 String url="http://www.baidu.com";
- 26 Handler handler = new Handler();
- 27 @Override
- 28 protected void onCreate(Bundle savedInstanceState) {
- 29 super.onCreate(savedInstanceState);
- 30 setContentView(R.layout.activity_main);
- 31
- 32 tvResult=(TextView)findViewById(R.id.textView1);
- 33 }
- 34
- 35 public void ClickButton(View view){
- 36 new Thread(new Runnable() {
- 37
- 38 @Override
- 39 public void run() {
- 40 // 获取HttpClient对象
- 41 HttpClient httpClient = new DefaultHttpClient();
- 42 // 获取HttpGet对象
- 43 HttpGet requestGet = new HttpGet(url);
- 44 try {
- 45 // 获取响应结果
- 46 HttpResponse httpResponse = httpClient.execute(requestGet);
- 47 if (httpResponse.getStatusLine().getStatusCode() == 200) {
- 48 // 从响应中取出实体类
- 49 HttpEntity httpEntity = httpResponse.getEntity();
- 50 final String result=EntityUtils.toString(httpEntity);
- 51 // 如果想通过IO流来读写可以使用getContent方法获取
- 52 //InputStream in = httpEntity.getContent();
- 53 handler.post(new Runnable() {
- 54
- 55 @Override
- 56 public void run() {
- 57 tvResult.setText(result);
- 58 }
- 59 });
- 60 }
- 61 } catch (Exception e) {
- 62 e.printStackTrace();
- 63
- 64 }
- 65 }
- 66 }).start();
- 67
- 68
- 69 }
- 70 @Override
- 71 public boolean onCreateOptionsMenu(Menu menu) {
- 72 // Inflate the menu; this adds items to the action bar if it is present.
- 73 getMenuInflater().inflate(R.menu.main, menu);
- 74 return true;
- 75 }
- 76
- 77 }
版权声明:本文为jingtonglong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。