URLConnection 类是一个抽象类,代表应用程序和URL之间的通信连接,此类的实例可用于读取和写入此URL引用的资源。URLConnection 允许使用GET,POST或者其他HTTP方法请求方式将请求数据发送到服务器。使用URLConnection对象一般分为以下7步(有的步骤并不是必要)。
1:创建一个URL对象;
2:通过URL对象的openConnection方法创建URLConnection对象;
3:通过URLConnection对象提供的方法可以设置参数和一般请求属性。常用的请求属性设置方式有以下几种:
~public void setRequestProperty(String key,String value)设置指定的请求关键字对应的值
~public void setDoInput(boolean doinput)设置是否使用URL连接进行输入,默认值为true
~public void setDoOutput(boolean dooutput)设置是否使用URL连接进行输出,默认值为false,如果设置为true,就可以获取一个字节输出流,用于将数据发送到服务器
~public void setUseCaches(boolean usecaches)设置此连接是否使用任何可用的缓存,默认值为true
4:调用URLConnection对象的connect方法连接到该远程资源
5:连接到服务器后,就可以查询头部信息了,查询头部信息常用方法有以下几种:
~public String getHeaderField(String name)返回指定头字段的值
~public Map<String,List<String>>getHeaderFields()返回头字段的不可修改的Map
~public String getContentType()返回content-type头字段的值
~public String getContentEncoding()返回content-encoding的值
6:获取输入流访问资源数据。使用getInputStream 方法,获取一个字节输入流,以便读取资源信息
7:获取输出流并写数据
下面用两个实例来演示一下用法:
1.使用URLConnection类来获取web服务器的数据
import java.net.*; import java.io.*; import java.util.*; public class URLGetTest { public static void main(String args[]){ //1.创建一个URL对象 URL url = null; BufferedReader br = null; try{ url = new URL("https://www.baidu.com/?tn=94461071_hao_pg"); //2.通过URL对象提出的openConnection方法创建URLConnection对象 URLConnection connection = url.openConnection(); //4.调用URLConnection对象提供的connect方法连接远程服务 connection.connect(); //5.连接服务器后,就可以查询头部信息了 Map<String,List<String>> headerMap = connection.getHeaderFields(); for(Map.Entry<String, List<String>> entry : headerMap.entrySet()){ String key = entry.getKey(); List<String> values = entry.getValue(); StringBuilder sb = new StringBuilder(); int size=values==null?0:values.size(); for(int i=0;i<size;i++){ if(i>0){ sb.append(","); } sb.append(values.get(i)); } System.out.println(key+":"+sb.toString()); } System.out.println("--------------------------"); //6.获取输入流,从中读取资源数据 InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); //遍历得到的数据 for(String line =null; (line=br.readLine())!=null;){ System.out.println(line); } } catch(MalformedURLException e){ e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } finally{ if(br!= null){ try{ br.close(); } catch(Exception ex){ ex.printStackTrace(); } } } } }</span>
<span style="font-size:18px;color:#000099;">此处为代码执行的输出结果:</span>
<span style="font-size:18px;">null:HTTP/1.1 200 OK Server:bfe/1.0.8.14 Connection:keep-alive Pragma:no-cache Last-Modified:Thu, 09 Oct 2014 10:47:57 GMT P3P:CP=" OTI DSP COR IVA OUR IND COM ",CP=" OTI DSP COR IVA OUR IND COM " Date:Mon, 11 Apr 2016 12:55:38 GMT Accept-Ranges:bytes X-UA-Compatible:IE=Edge,chrome=1 Set-Cookie:__bsi=13204254035449457344_00_361_N_N_4_0303_C02F_N_N_N_0; expires=Mon, 11-Apr-16 12:55:43 GMT; domain=www.baidu.com; path=/,BDRCVFR[yyDPslwKIr3]=mk3SLVN4HKm; path=/; domain=.baidu.com,PSTM=1460379338; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com,BIDUPSID=27358CE3934CB05992517CFA781FD62B; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com,BD_NOT_HTTPS=1; path=/; Max-Age=300 Content-Length:227 Cache-control:no-cache Content-Type:text/html -------------------------- <html> <head> <span style="white-space:pre"> </span><script> <span style="white-space:pre"> </span>location.replace(location.href.replace("https://","http://")); <span style="white-space:pre"> </span></script> </head> <body> <span style="white-space:pre"> </span><noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript> </body> </html> </span>
<span style="font-size:18px;"> </span>
<span style="font-size:18px;"> </span>
<span style="background-color: rgb(255, 255, 255);"><span style="color:#000099;">2.使用URLConnection向web服务器发送表单数据并接受服务器返回的响应数据</span></span>
import java.net.*; import java.io.*; import java.util.*; //发送表单数据 public class URLSendTest { public static void main(String args[]){ Properties props = new Properties(); props.setProperty("Content-type", "application/x-www-form-urlencoded"); props.setProperty("q","java"); props.setProperty("p", "2"); try{ //1,创建一个url sendPostResquest(new URL("http://so.csdn.net/"),props); } catch(IOException e){ e.printStackTrace(); } } public static void sendPostResquest(URL url,Properties nameValue) throws IOException{ //2,通过URL对象的openConnection创建URLConnection HttpURLConnection con = (HttpURLConnection)url.openConnection(); //3,post请求的参数名/值队要放在HTTP正文中 con.setDoOutput(true);//设置是否使用URL连接进行输出 //4.把请求参数添加到连接对象中 OutputStream os = con.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); PrintWriter pw = new PrintWriter(osw,true); for(Iterator it = nameValue.keySet().iterator();it.hasNext();){ String key = (String) it.next(); String values = nameValue.getProperty(key); pw.write(key); pw.write("="); pw.write(values); if(it.hasNext()){ pw.write("&"); } } pw.close(); //4.连接 con.connect(); //6.获取输入流用来读取数据 InputStream is = con.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); //遍历输出读取到的数据 for(String value = null;(value=br.readLine())!=null;){ System.out.println(value); } } }
<span style="color:#000099;">此处向http://so.csdn.net/发送了一个请求,请求参数为“q=java”,表示要查询包含“java”关键字的文章,请求参数“p=2”表示要查询第三页的内容,查询结果(部分)如下:</span>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <span style="white-space:pre"> </span><head> <span style="white-space:pre"> </span><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <span style="white-space:pre"> </span><title>CSDN鎼滅储</title> <span style="white-space:pre"> </span><link href="http://c.csdnimg.cn/public/common/toolbar/css/index.css" rel="stylesheet" > <span style="white-space:pre"> </span><link type="text/css" href="/so/css/main.css" rel="stylesheet"> <span style="white-space:pre"> </span><script type="text/javascript" src="http://csdnimg.cn/public/common/libs/jquery/jquery-1.9.1.min.js"></script>