网络编程之URL和URLConnection
2016-07-19 15:19
495 查看
网络编程之URL和URLConnection
介绍
URL和URLConnection类是完成http网络请求时所用到的两个对象 The java.net package contains two interesting classes: The URL class and the URLConnection class. these classes can be used to create client connections to web servers (HTTP servers).
URL
java中URL类代表了日常所使用的url(统一资源定位符),我们当然也可以使用字符串来代替url, 不过java是面向对象编程语言因此使用URL对象来表示。 Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object,such as a query to a database or to a search engine.
核心方法
/** * URL类中定义了很多方法,能够操作大部分url里面的内容,URL类定义和url语法格式一致。所以操作起来也很方便。 * * 最常用的两个方法 * URL(String url);构造方法 URLConnection * openConnection();获得URLConnection连接对象 */ // 初始化URL对象 URL url = new URL("url 地址"); // 根据URL对象获得连接对象 URLConnection connection = url.openConnection();
URLConnection
URLConnection表示一个连接对象,通过这个对象我们可以做很多事情(获得响应信息)。 URLConnection其实是一个抽象类,其主要实现有HttpURLConnection和JarURLConnection类, 绝大多数情况下我们是使用HttpURLConnection类的。 The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL.
核心方法
abstract public class HttpURLConnection extends URLConnection { public void setRequestMethod(String method) throws ProtocolException {}//重点掌握 public int getResponseCode() throws IOException {}//重点掌握 //Returns an input stream that reads from this open connection. //设置输入流就是为了获得请求体里的数据 public InputStream getInputStream() throws IOException {}//重点掌握 //Returns an output stream that writes to this connection. //获得这个输出流其实就是为了向请求体里增加数据 public OutputStream getOutputStream() throws IOException {}//重点掌握 //设置从HttpURLConnection对象能否获得输入和输出流 public void setDoInput(boolean doinput) {}//默认为true(因为很常用所以设置为true),重点掌握 //如果是post方法时,就一定要设置为true public void setDoOutput(boolean dooutput) {}//默认为false,重点掌握 //Sets the general request property. If a property with the key already //exists, overwrite its value with the new value. //就是设置请求头信息 public void setRequestProperty(String key, String value) {} public Map<String,List<String>> getRequestProperties() {} } 我们可以使用URL和URLConnection来完成http请求组件工具,具体参考之前写的一篇文章
http://blog.csdn.net/nicewuranran/article/details/51756122
参考
1、http://tutorials.jenkov.com/java-networking/url-urlconnection.html2、https://en.wikipedia.org/wiki/Uniform_Resource_Locator
3、http://blog.csdn.net/nicewuranran/article/details/51756122