java对网络通信以及提供了比较全面的jdk支持,java.net包能让程序员直接在程序中实现网络通信。
在技术日新月异的现在,我们能通过很多方式实现数据通信,比如webservice、url通信、socket通信等等,今天简单介绍下URL通信。
学习准备:建议首先学习java的IO基础知识
URL是统一资源定位器的简写,URL可以访问Internet和www,可以通过url访问网络资源或文件。
java提供了java.net.URL类来封装URL,大家可以在jdk api中看该类的详细介绍。
下面写一个最简单的URL创建和使用方式:
URL url = new URL("http://www.baidu.com/"); System.out.println("授权部分:"+url.getAuthority()); System.out.println("网页内容:"+url.getContent()); System.out.println("默认端口:"+url.getDefaultPort()); System.out.println("文件名:"+url.getFile()); System.out.println("主机名:"+url.getHost()); System.out.println("路径名:"+url.getPath()); System.out.println("端口号:"+url.getPort()); System.out.println("协议名:"+url.getProtocol()); System.out.println("查询部分:"+url.getQuery()); System.out.println("锚点:"+url.getRef()); System.out.println("userInfo:"+url.getUserInfo()); String charSet = "gb2312"; System.out.println("--------------getContent获取网页内容-------------------"); //获取并打印url页面的html源文件 InputStream in = (InputStream) url.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(in,charSet)); String s = br.readLine() ; while(s!=null){ System.out.println(s); s = br.readLine(); } br.close(); in.close();
有了URL还不够,它只能获得URL本身的基本信息,如果要实现通信,需要使用URLConnection(如果是http通信,可以使用它的子类HttpURLConnection)。通过url的openConnection方法可以打开连接。
URLConnection urlConn = new URL(url).openConnection();
HttpURLConnection httpConn = (HttpURLConnection)new URL(url).openConnection();
HttpURLConnection有两种请求方式:POST和GET,跟平常J2EE项目一样。可以通过设置setRequestMethod来配置请求方式:
httpConn.setRequestMethod("POST");
httpConn.setRequestMethod("GET");
注意请求方式字符串需要大写,如果请求方式有误,会抛出ProtocolException异常
POST和GET发送请求方式有所不同:POST向指定服务器发送的信息是被封装在http内部,而GET发送请求是通过http地址后拼接参数信息(http://www.xx.xx?xx=xx&xxx=xx)实现的。POST向服务器发送信息的时候是把请求信息以IO“流”的形式发送,而GET方式无法通过“流”形式传输。
下面代码通过GET方式发送请求:
String urlString = "http://localhost:8080/TestConn/Conn"; //传递一条参数 urlString += "?id=1"; URL url = new URL(urlString); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection() httpConn.setRequestMethod("GET"); //调用connect方法执行通信 httpConn.connect();
下面代码通过POST方式发送请求:
String urlString = "http://localhost:8080/TestConn/Conn"; URL url = new URL(urlString); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection() httpConn.setRequestMethod("POST"); //设置是否向httpUrlConnection输出,如果是POST请求,则需要设为true, 默认情况下是false; httpConn.setDoInput(true); //设置是否从httpUrlConnection读入,默认情况下是true; httpConn.setDoOutput(true); //Post请求不能使用缓存 httpConn.setUseCaches(true); //设定传送的内容类型是可序列化的java对象 httpConn.setRequestProperty("Content-type", "application/x-java-serialized-object"); //创建输出流发送请求数据 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(httpConn.getOutputStream())); bw.write(new String("我勒个去...")); bw.flush(); bw.close();
注意:一旦使用了httpConn.getOutputStream().write()方法,httpConn.setRequestMethod("GET");将失效,其请求方法会自动转为POST
服务器处理GET请求的时候通过request.getParameter方式获取请求参数,POST请求通过request.getInputStream流的形式获取。
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String s = request.getParameter("id"); response.setCharacterEncoding("UTF-8"); response.getWriter().print(s); response.getWriter().close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取IO数据 BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuffer sb = new StringBuffer(); String s; while((s = br.readLine())!=null){ sb.append(s); sb.append("\n"); } response.setCharacterEncoding("UTF-8"); response.getWriter().print(sb.toString()); response.getWriter().close(); }
获取服务器响应数据的时候可以通过IO的输入流取得:
public static String getInput(HttpURLConnection http) throws IOException{ //获取指定URL返回的IO数据 InputStream in = http.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); StringBuffer sb = new StringBuffer(); String s; while((s = br.readLine())!=null){ sb.append(s); sb.append("\n"); } br.close(); in.close(); return sb.toString(); }
下面用一个完整代码总结下URL通信的方法:
public static void main(String[] args) throws IOException { //①创建URL对象(如果是GET请求,则url后要拼接请求参数) String urlString = "http://localhost:8080/TestConn/Conn"; URL url = new URL(urlString); //②创建HttpUrlConnection对象 HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); //③配置httpConn的属性 httpConn.setRequestMethod("POST"); httpConn.setDoInput(true); httpConn.setDoOutput(true); httpConn.setUseCaches(true); httpConn.setRequestProperty("Content-type", "application/x-java-serialized-object"); //④发送请求信息(为什么使用字符缓冲流,这纯属个人爱好) BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(httpConn.getOutputStream())); bw.write("Hello URL...\n"); bw.write("你好 ItEye..."); bw.flush(); bw.close(); //⑤获取响应信息 BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); String response = null; while((response = br.readLine())!=null){ System.out.println(response); } br.close(); //⑥通信结束.... }
注意:http://localhost:8080/TestConn/Conn请求的是一个servlet,代码写在本文中间偏下位置。
URL通信技术入门很简单,一天时间足矣。