当前位置:首页 > 芯闻号 > 充电吧
[导读]public abstract class HttpURLConnection extends URLConnectionjava.lang.Object    ↳ java.net.URLCon

public abstract class HttpURLConnection extends URLConnection
java.lang.Object    ↳ java.net.URLConnection      ↳ java.net.HttpURLConnection
1、获取HttpURLConnection实例
HttpURLConnection(URL url)Constructs a new HttpURLConnection instance pointing to the resource specified by theurl.
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);


访问百度首页:


Protected Constructors
本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭