public abstract class
HttpURLConnection
extends URLConnectionjava.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 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);
访问百度首页:
完整代码在:https://github.com/HiSunny/ComeOnHttpURLConnection.git