简单使用URLConnection、HttpURLConnection和HttpClient访问网络资源

http://blog.csdn.net/u010142437/article/details/9348867

URL的openConnection方法将返回一个URLConnection,该对象表示应用程序和URL之间的通信连接。程序可以通过它的实例向该URL发送请求,读取URL引用的资源。

下面通过一个简单示例来演示:

Activity:

  1. package com.home.urlconnection;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7. import java.net.URLConnection;  
  8. import java.util.ArrayList;  
  9. import java.util.List;  
  10.   
  11. import org.apache.http.HttpEntity;  
  12. import org.apache.http.HttpResponse;  
  13. import org.apache.http.client.ClientProtocolException;  
  14. import org.apache.http.client.HttpClient;  
  15. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  16. import org.apache.http.client.methods.HttpPost;  
  17. import org.apache.http.impl.client.DefaultHttpClient;  
  18. import org.apache.http.message.BasicNameValuePair;  
  19. import org.apache.http.util.EntityUtils;  
  20.   
  21. import android.app.Activity;  
  22. import android.os.Bundle;  
  23. import android.view.View;  
  24. import android.view.View.OnClickListener;  
  25. import android.webkit.WebView;  
  26. import android.widget.Button;  
  27. import android.widget.TextView;  
  28.   
  29. public class MainActivity extends Activity implements OnClickListener {  
  30.     private Button urlConnectionBtn;  
  31.     private Button httpUrlConnectionBtn;  
  32.     private Button httpClientBtn;  
  33.     private TextView showTextView;  
  34.     private WebView webView;  
  35.   
  36.     @Override  
  37.     protected void onCreate(Bundle savedInstanceState) {  
  38.         super.onCreate(savedInstanceState);  
  39.         setContentView(R.layout.activity_main);  
  40.         init();  
  41.     }  
  42.   
  43.     private void init() {  
  44.         urlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_urlconnection);  
  45.         httpUrlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_httpurlconnection);  
  46.         httpClientBtn = (Button) findViewById(R.id.test_url_main_btn_httpclient);  
  47.         showTextView = (TextView) findViewById(R.id.test_url_main_tv_show);  
  48.         webView = (WebView) findViewById(R.id.test_url_main_wv);  
  49.         urlConnectionBtn.setOnClickListener(this);  
  50.         httpUrlConnectionBtn.setOnClickListener(this);  
  51.         httpClientBtn.setOnClickListener(this);  
  52.     }  
  53.   
  54.     @Override  
  55.     public void onClick(View v) {  
  56.         if (v == urlConnectionBtn) {  
  57.             try {  
  58.                 // 直接使用URLConnection对象进行连接   
  59.                 URL url = new URL("http://192.168.1.100:8080/myweb/hello.jsp");  
  60.                 // 得到URLConnection对象   
  61.                 URLConnection connection = url.openConnection();  
  62.                 InputStream is = connection.getInputStream();  
  63.                 byte[] bs = new byte[1024];  
  64.                 int len = 0;  
  65.                 StringBuffer sb = new StringBuffer();  
  66.                 while ((len = is.read(bs)) != -1) {  
  67.                     String str = new String(bs, 0, len);  
  68.                     sb.append(str);  
  69.                 }  
  70.                 showTextView.setText(sb.toString());  
  71.             } catch (Exception e) {  
  72.                 e.printStackTrace();  
  73.             }  
  74.         }  
  75.         if (v == httpUrlConnectionBtn) {  
  76.             // 直接使用HttpURLConnection对象进行连接   
  77.             try {  
  78.                 URL url = new URL(  
  79.                         "http://192.168.1.100:8080/myweb/hello.jsp?username=abc");  
  80.                 // 得到HttpURLConnection对象   
  81.                 HttpURLConnection connection = (HttpURLConnection) url  
  82.                         .openConnection();  
  83.                 // 设置为GET方式   
  84.                 connection.setRequestMethod("GET");  
  85.                 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {  
  86.                     // 得到响应消息   
  87.                     String message = connection.getResponseMessage();  
  88.                     showTextView.setText(message);  
  89.                 }  
  90.             } catch (Exception e) {  
  91.                 e.printStackTrace();  
  92.             }  
  93.         }  
  94.         if (v == httpClientBtn) {  
  95.             try {  
  96.                 // 使用ApacheHttp客户端进行连接(重要方法)   
  97.                 HttpClient client = new DefaultHttpClient();  
  98.   
  99.                 // 如果是Get提交则创建HttpGet对象,否则创建HttpPost对象   
  100.                 // POST提交的方式   
  101.                 HttpPost httpPost = new HttpPost(  
  102.                         "http://192.168.1.100:8080/myweb/hello.jsp");  
  103.                 // 如果是Post提交可以将参数封装到集合中传递   
  104.                 List dataList = new ArrayList();  
  105.                 dataList.add(new BasicNameValuePair("username""abc"));  
  106.                 dataList.add(new BasicNameValuePair("pwd""123"));  
  107.                 // UrlEncodedFormEntity用于将集合转换为Entity对象   
  108.                 httpPost.setEntity(new UrlEncodedFormEntity(dataList));  
  109.   
  110.                 // GET提交的方式   
  111.                 // HttpGet httpGet = new   
  112.                 // HttpGet("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");   
  113.   
  114.                 // 获取相应消息   
  115.                 HttpResponse httpResponse = client.execute(httpPost);  
  116.                 // 获取消息内容   
  117.                 HttpEntity entity = httpResponse.getEntity();  
  118.                 // 把消息对象直接转换为字符串   
  119.                 String content = EntityUtils.toString(entity);  
  120.                 // 显示在TextView中   
  121.                 // showTextView.setText(content);   
  122.   
  123.                 // 通过webview来解析网页   
  124.                 webView.loadDataWithBaseURL(null, content, "text/html",  
  125.                         "utf-8"null);  
  126.                 // 直接根据url来进行解析   
  127.                 // webView.loadUrl(url);   
  128.             } catch (ClientProtocolException e) {  
  129.                 e.printStackTrace();  
  130.             } catch (IOException e) {  
  131.                 e.printStackTrace();  
  132.             }  
  133.         }  
  134.     }  
  135.   
  136. }  
package com.home.urlconnection;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
	private Button urlConnectionBtn;
	private Button httpUrlConnectionBtn;
	private Button httpClientBtn;
	private TextView showTextView;
	private WebView webView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
	}

	private void init() {
		urlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_urlconnection);
		httpUrlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_httpurlconnection);
		httpClientBtn = (Button) findViewById(R.id.test_url_main_btn_httpclient);
		showTextView = (TextView) findViewById(R.id.test_url_main_tv_show);
		webView = (WebView) findViewById(R.id.test_url_main_wv);
		urlConnectionBtn.setOnClickListener(this);
		httpUrlConnectionBtn.setOnClickListener(this);
		httpClientBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == urlConnectionBtn) {
			try {
				// 直接使用URLConnection对象进行连接
				URL url = new URL("http://192.168.1.100:8080/myweb/hello.jsp");
				// 得到URLConnection对象
				URLConnection connection = url.openConnection();
				InputStream is = connection.getInputStream();
				byte[] bs = new byte[1024];
				int len = 0;
				StringBuffer sb = new StringBuffer();
				while ((len = is.read(bs)) != -1) {
					String str = new String(bs, 0, len);
					sb.append(str);
				}
				showTextView.setText(sb.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (v == httpUrlConnectionBtn) {
			// 直接使用HttpURLConnection对象进行连接
			try {
				URL url = new URL(
						"http://192.168.1.100:8080/myweb/hello.jsp?username=abc");
				// 得到HttpURLConnection对象
				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				// 设置为GET方式
				connection.setRequestMethod("GET");
				if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
					// 得到响应消息
					String message = connection.getResponseMessage();
					showTextView.setText(message);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (v == httpClientBtn) {
			try {
				// 使用ApacheHttp客户端进行连接(重要方法)
				HttpClient client = new DefaultHttpClient();

				// 如果是Get提交则创建HttpGet对象,否则创建HttpPost对象
				// POST提交的方式
				HttpPost httpPost = new HttpPost(
						"http://192.168.1.100:8080/myweb/hello.jsp");
				// 如果是Post提交可以将参数封装到集合中传递
				List dataList = new ArrayList();
				dataList.add(new BasicNameValuePair("username", "abc"));
				dataList.add(new BasicNameValuePair("pwd", "123"));
				// UrlEncodedFormEntity用于将集合转换为Entity对象
				httpPost.setEntity(new UrlEncodedFormEntity(dataList));

				// GET提交的方式
				// HttpGet httpGet = new
				// HttpGet("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");

				// 获取相应消息
				HttpResponse httpResponse = client.execute(httpPost);
				// 获取消息内容
				HttpEntity entity = httpResponse.getEntity();
				// 把消息对象直接转换为字符串
				String content = EntityUtils.toString(entity);
				// 显示在TextView中
				// showTextView.setText(content);

				// 通过webview来解析网页
				webView.loadDataWithBaseURL(null, content, "text/html",
						"utf-8", null);
				// 直接根据url来进行解析
				// webView.loadUrl(url);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}

上面使用到的url是部署在笔者本机的web应用,这里不再给出,大家可以换成自己的web应用即可。
布局XML:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <Button  
  8.         android:id="@+id/test_url_main_btn_urlconnection"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="使用URLConnection连接" />  
  12.   
  13.     <Button  
  14.         android:id="@+id/test_url_main_btn_httpurlconnection"  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="使用HttpURLConnection连接" />  
  18.   
  19.     <Button  
  20.         android:id="@+id/test_url_main_btn_httpclient"  
  21.         android:layout_width="wrap_content"  
  22.         android:layout_height="wrap_content"  
  23.         android:text="使用Apache客户端连接" />  
  24.   
  25.     <TextView  
  26.         android:id="@+id/test_url_main_tv_show"  
  27.         android:layout_width="wrap_content"  
  28.         android:layout_height="wrap_content" />  
  29.   
  30.     <WebView  
  31.         android:id="@+id/test_url_main_wv"  
  32.         android:layout_width="match_parent"  
  33.         android:layout_height="match_parent" />  
  34.   
  35. </LinearLayout>  
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/test_url_main_btn_urlconnection"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="使用URLConnection连接" />

    <Button
        android:id="@+id/test_url_main_btn_httpurlconnection"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="使用HttpURLConnection连接" />

    <Button
        android:id="@+id/test_url_main_btn_httpclient"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="使用Apache客户端连接" />

    <TextView
        android:id="@+id/test_url_main_tv_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

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

</LinearLayout>

权限:

  1. <uses-permission android:name="android.permission.INTERNET" />  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值