使用Http协议访问网络--HttpURLConnection

HttpURLConnection

extends URLConnection
java.lang.Object
   ↳java.net.URLConnection
    ↳java.net.HttpURLConnection

1、获取HttpURLConnection实例

Protected Constructors
HttpURLConnection( URL url)
Constructs a new HttpURLConnection instance pointing to the resource specified by the url.

HttpURLConnection是abstract的,不能new出实例。一般new出一个URL对象并传入目标网络地址,然后调用openConnection()方法。
URL url = new URL("http://www.baidu.com");
//public URLConnection openConnection () 
//Returns a new connection to the resource referred to by this URL.
//向url发出HTTP请求的HttpURLConnection实例
//Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection
connection =  (HttpURLConnection)url.openConnection();
2、对 HttpURLConnection实例设置HTTP请求所使用的方法,连接超时等
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
3、调用connection.getInputStream()获得到服务器返回的输入流(连接发生),对输入流读取
//发生连接(在其之前设置好参数)
InputStream in = connection.getInputStream();//同url.openStream();可以不用connection
//java.io.BufferedReader.BufferedReader(Reader in)
//Constructs a new BufferedReader, providing in with a buffer of 8192 characters.
//public class BufferedReader extends Reader
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder responseStringBuilder = new StringBuilder();
String lineStr ;
while((lineStr = reader.readLine())!= null){
	responseStringBuilder.append(lineStr);
					}

Android4.0后,网络操作要在子线程中进行。
采用Handler、Message发送消息。
 
private Handler handler = new Handler(){
		public void handleMessage(Message msg){
			switch(msg.what){
			case SHOW_RESPONSE:
				String response = (String)msg.obj;
				responseTextView.setText(response);
				break;
			default:
				break;
			
			}
		}
	};

Message message = Message.obtain(mHandler, SEND_REQUEST, responseString);
mHandler.sendMessage(message);

访问百度首页:

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值