WebView,HttpURLConnection,HttpClient的简单使用

这篇博客介绍了Android中WebView的基本使用,包括在布局文件中添加WebView并设置网络访问权限。接着,讲解了如何使用HttpURLConnection向百度发送请求并获取响应。最后,提到了HttpClient作为Apach提供的HTTP网络访问接口,其简单易用的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、WebView的简单使用

安卓程序有的需要浏览网页,因此android提供了一个控件叫WebView,话不多说,直接使用


界面布局代码,就显示一个WebView

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >


    <WebView
        android:id="@+id/main_show_webView" 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        
        />
</RelativeLayout>


处理的代码

public class MainActivity extends Activity {
	
	private WebView mShowWebView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		//设置隐藏标题
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mShowWebView=(WebView) findViewById(R.id.main_show_webView);
		
		//通过getSettings进行设置,然后设置支持javaScript
		mShowWebView.getSettings().setJavaScriptEnabled(true);
		
		mShowWebView.setWebViewClient(new WebViewClient(){
			@Override
			//该方法表明如果从当前网页跳转到别的网页,还是在当前的webView中显示,不使用系统的浏览器
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
		});
		//加载页面
		mShowWebView.loadUrl("http://www.baidu.com");
	}
}



注意设置网络访问权限



2、HttpURLConnection的简单使用


写一个小例子,向百度发送请求,然后得到请求结果

界面布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <Button 
        android:id="@+id/second_sendButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="sendRequestWithHttpURLConnection"
        />
  
    
    <ScrollView 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
       <TextView
           android:id="@+id/second_responseTextView" 
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           />
        
    </ScrollView>

    

</LinearLayout>
处理代码(解释见代码注释)

public class SecondActivity extends Activity {

	private Button mSendButton;
	
	private TextView mShowTextView;
	
	private Handler mHandler;
	
	private static final String TAG="SecondActivity";
	
	private static final int SEND_REQUEST=1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_second);
		mSendButton=(Button) findViewById(R.id.second_sendButton);
		
		mShowTextView=(TextView) findViewById(R.id.second_responseTextView);
		//通过handler接收到从网页获取到的数据,在主线程进行更新
		mHandler=new Handler(){
			public void handleMessage(android.os.Message msg) {
				if(msg.what==SEND_REQUEST){
					StringBuilder result=(StringBuilder) msg.obj;
					mShowTextView.setText(result);
				}
			};
		};
		
		mSendButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				sendRequestWithHttpURLConection();
			}
		});
	}
	
	private void sendRequestWithHttpURLConection(){
		//由于访问网络是耗时操作,因此开一个子线程
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				HttpURLConnection connection=null;
				try {
					URL url=new URL("http://www.baidu.com");
					//通过给定的url获得connection
					connection=(HttpURLConnection) url.openConnection();
					//设置请求方法,GET表明从获得数据
					connection.setRequestMethod("GET");
					//设置超时操作
					connection.setReadTimeout(5000);
					connection.setConnectTimeout(5000);
					//得到输入流
					InputStream in=connection.getInputStream();
					//通过输入流读取数据
					BufferedReader reader=new BufferedReader(new InputStreamReader(in));
					
					StringBuilder content=new StringBuilder();
					String line="";
					
					while((line=reader.readLine())!=null){
						content.append(line);
					}
					
					//将得到的结果通过handler发送到主线程,在主线程进行UI操作
					Message msg=mHandler.obtainMessage(SEND_REQUEST,content);
					mHandler.sendMessage(msg);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				
				}
			}
		}).start();
	}

}




3、HttpClient

HttpClient是Apche提供的HTTP网络访问接口,使用比较简单,因为他对一些参数都进行了封装,解释见代码注释

界面代码略

private void sendRequestWithHttpClient() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				
				try {
					//HttpClient是一个接口,因此一般new DefaultHttpClient
					HttpClient client=new DefaultHttpClient();
					//获得HttpClient
					HttpGet get=new HttpGet("www.baidu.com");
					//执行get请求,得到responce
					HttpResponse response=client.execute(get);
					//判断是否成功
					if(response.getStatusLine().getStatusCode()==200){
						//通过EntityUtils将返回内容转化成字符串
						String content=EntityUtils.toString(response.getEntity(), "ytf-8");
						//发送给mHandler
						 Message msg = mHandler.obtainMessage(SHOW_RESPONSE,
						 content); mHandler.sendMessage(msg);
					}
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
				
				
		}).start();
	}


结果略

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值