封装 HttpURLConnection

HttpURLConnection为javaAPI提供的一种Rest访问的方式。其支持对Post,Delete,Get,Put等方式的访问。

以下为对于HttpURLConnection对Post等方式访问的一段代码。

  1. package  com.sw.study.urlConnection;  
  2.   
  3. import  java.io.BufferedReader;  
  4. import  java.io.InputStreamReader;  
  5. import  java.io.OutputStream;  
  6. import  java.net.HttpURLConnection;  
  7. import  java.net.URL;  
  8. import  java.net.URLConnection;  
  9. import  java.util.HashMap;  
  10. import  java.util.Map;  
  11.   
  12. public   class  URLConnectionUtil {  
  13.       
  14.     private   static   final  String SERVLET_POST =  "POST"  ;  
  15.     private   static   final  String SERVLET_GET =  "GET"  ;  
  16.     private   static   final  String SERVLET_DELETE =  "DELETE"  ;  
  17.     private   static   final  String SERVLET_PUT =  "PUT"  ;  
  18.       
  19.     private   static  String prepareParam(Map<String,Object> paramMap){  
  20.         StringBuffer sb = new  StringBuffer();  
  21.         if (paramMap.isEmpty()){  
  22.             return   ""  ;  
  23.         }else {  
  24.             for (String key: paramMap.keySet()){  
  25.                 String value = (String)paramMap.get(key);  
  26.                 if (sb.length()< 1 ){  
  27.                     sb.append(key).append("=" ).append(value);  
  28.                 }else {  
  29.                     sb.append("&" ).append(key).append( "=" ).append(value);  
  30.                 }  
  31.             }  
  32.             return  sb.toString();  
  33.         }  
  34.     }  
  35.       
  36.     public   static   void   doPost(String urlStr,Map<String,Object> paramMap )  throws Exception{  
  37.         URL url = new  URL(urlStr);  
  38.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  39.         conn.setRequestMethod(SERVLET_POST);  
  40.         String paramStr = prepareParam(paramMap);  
  41.         conn.setDoInput(true );  
  42.         conn.setDoOutput(true );  
  43.         OutputStream os = conn.getOutputStream();       
  44.         os.write(paramStr.toString().getBytes("utf-8" ));       
  45.         os.close();           
  46.           
  47.         BufferedReader br = new  BufferedReader( new InputStreamReader(conn.getInputStream()));  
  48.         String line ;  
  49.         String result ="" ;  
  50.         while ( (line =br.readLine()) !=  null  ){  
  51.             result += "/n" +line;  
  52.         }  
  53.         System.out.println(result);  
  54.         br.close();  
  55.           
  56.     }  
  57.       
  58.     public   static   void   doGet(String urlStr,Map<String,Object> paramMap )  throws Exception{  
  59.         String paramStr = prepareParam(paramMap);  
  60.         if (paramStr ==  null  || paramStr.trim().length()< 1 ){  
  61.               
  62.         }else {  
  63.             urlStr +="?" +paramStr;  
  64.         }  
  65.         System.out.println(urlStr);  
  66.         URL url = new  URL(urlStr);  
  67.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  68.         conn.setRequestMethod(SERVLET_PUT);  
  69.         conn.setRequestProperty("Content-Type" , "text/html; charset=UTF-8" );  
  70.           
  71.         conn.connect();  
  72.         BufferedReader br = new  BufferedReader( new InputStreamReader(conn.getInputStream()));  
  73.         String line ;  
  74.         String result ="" ;  
  75.         while ( (line =br.readLine()) !=  null  ){  
  76.             result += "/n" +line;  
  77.         }  
  78.         System.out.println(result);  
  79.         br.close();  
  80.     }  
  81.       
  82.     public   static   void  doPut(String urlStr,Map<String,Object> paramMap)  throws Exception{  
  83.         URL url = new  URL(urlStr);  
  84.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  85.         conn.setRequestMethod(SERVLET_PUT);  
  86.         String paramStr = prepareParam(paramMap);  
  87.         conn.setDoInput(true );  
  88.         conn.setDoOutput(true );  
  89.         OutputStream os = conn.getOutputStream();       
  90.         os.write(paramStr.toString().getBytes("utf-8" ));       
  91.         os.close();           
  92.           
  93.         BufferedReader br = new  BufferedReader( new InputStreamReader(conn.getInputStream()));  
  94.         String line ;  
  95.         String result ="" ;  
  96.         while ( (line =br.readLine()) !=  null  ){  
  97.             result += "/n" +line;  
  98.         }  
  99.         System.out.println(result);  
  100.         br.close();  
  101.                   
  102.     }  
  103.       
  104.     public   static   void  doDelete(String urlStr,Map<String,Object> paramMap)  throws Exception{  
  105.         String paramStr = prepareParam(paramMap);  
  106.         if (paramStr ==  null  || paramStr.trim().length()< 1 ){  
  107.               
  108.         }else {  
  109.             urlStr +="?" +paramStr;  
  110.         }     
  111.         System.out.println(urlStr);  
  112.         URL url = new  URL(urlStr);  
  113.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  114.         conn.setDoOutput(true );  
  115.         conn.setRequestMethod(SERVLET_DELETE);  
  116.         //屏蔽掉的代码是错误的,java.net.ProtocolException: HTTP method DELETE doesn't support output   
  117. /*      OutputStream os = conn.getOutputStream();       
  118.         os.write(paramStr.toString().getBytes("utf-8"));       
  119.         os.close();  */    
  120.           
  121.         if (conn.getResponseCode() == 200 ){  
  122.             System.out.println("成功" );  
  123.         }else {  
  124.             System.out.println(conn.getResponseCode());  
  125.         }  
  126.     }  
  127.       
  128.     public   static   void  main(String[] args)  throws  Exception{  
  129.         String urlStr = "http://localhost:8080/SwTest/ReceiveDataServlet" ;  
  130.         Map<String,Object> map = new  HashMap<String,Object>();  
  131.         map.put("username" , "张三" );  
  132.         map.put("password" , "88888" );  
  133. //      URLConnectionUtil.doGet(urlStr, map);   
  134. //      URLConnectionUtil.doPost(urlStr, map);   
  135. //      URLConnectionUtil.doPut(urlStr, map);   
  136.         URLConnectionUtil.doDelete(urlStr, map);  
  137.           
  138.     }  
  139.       
  140.       
  141. }  

 

  1. package com.sw.study.urlConnection;  
  2. import java.io.BufferedReader;  
  3. import java.io.InputStreamReader;  
  4. import java.io.OutputStream;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7. import java.net.URLConnection;  
  8. import java.util.HashMap;  
  9. import java.util.Map;  
  10. public class URLConnectionUtil {  
  11.       
  12.     private static final String SERVLET_POST = "POST" ;  
  13.     private static final String SERVLET_GET = "GET" ;  
  14.     private static final String SERVLET_DELETE = "DELETE" ;  
  15.     private static final String SERVLET_PUT = "PUT" ;  
  16.       
  17.     private static String prepareParam(Map<String,Object> paramMap){  
  18.         StringBuffer sb = new StringBuffer();  
  19.         if(paramMap.isEmpty()){  
  20.             return "" ;  
  21.         }else{  
  22.             for(String key: paramMap.keySet()){  
  23.                 String value = (String)paramMap.get(key);  
  24.                 if(sb.length()<1){  
  25.                     sb.append(key).append("=").append(value);  
  26.                 }else{  
  27.                     sb.append("&").append(key).append("=").append(value);  
  28.                 }  
  29.             }  
  30.             return sb.toString();  
  31.         }  
  32.     }  
  33.       
  34.     public static void  doPost(String urlStr,Map<String,Object> paramMap ) throws Exception{  
  35.         URL url = new URL(urlStr);  
  36.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  37.         conn.setRequestMethod(SERVLET_POST);  
  38.         String paramStr = prepareParam(paramMap);  
  39.         conn.setDoInput(true);  
  40.         conn.setDoOutput(true);  
  41.         OutputStream os = conn.getOutputStream();       
  42.         os.write(paramStr.toString().getBytes("utf-8"));       
  43.         os.close();           
  44.           
  45.         BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  46.         String line ;  
  47.         String result ="";  
  48.         while( (line =br.readLine()) != null ){  
  49.             result += "/n"+line;  
  50.         }  
  51.         System.out.println(result);  
  52.         br.close();  
  53.           
  54.     }  
  55.       
  56.     public static void  doGet(String urlStr,Map<String,Object> paramMap ) throws Exception{  
  57.         String paramStr = prepareParam(paramMap);  
  58.         if(paramStr == null || paramStr.trim().length()<1){  
  59.               
  60.         }else{  
  61.             urlStr +="?"+paramStr;  
  62.         }  
  63.         System.out.println(urlStr);  
  64.         URL url = new URL(urlStr);  
  65.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  66.         conn.setRequestMethod(SERVLET_PUT);  
  67.         conn.setRequestProperty("Content-Type","text/html; charset=UTF-8");  
  68.           
  69.         conn.connect();  
  70.         BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  71.         String line ;  
  72.         String result ="";  
  73.         while( (line =br.readLine()) != null ){  
  74.             result += "/n"+line;  
  75.         }  
  76.         System.out.println(result);  
  77.         br.close();  
  78.     }  
  79.       
  80.     public static void doPut(String urlStr,Map<String,Object> paramMap) throws Exception{  
  81.         URL url = new URL(urlStr);  
  82.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  83.         conn.setRequestMethod(SERVLET_PUT);  
  84.         String paramStr = prepareParam(paramMap);  
  85.         conn.setDoInput(true);  
  86.         conn.setDoOutput(true);  
  87.         OutputStream os = conn.getOutputStream();       
  88.         os.write(paramStr.toString().getBytes("utf-8"));       
  89.         os.close();           
  90.           
  91.         BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  92.         String line ;  
  93.         String result ="";  
  94.         while( (line =br.readLine()) != null ){  
  95.             result += "/n"+line;  
  96.         }  
  97.         System.out.println(result);  
  98.         br.close();  
  99.                   
  100.     }  
  101.       
  102.     public static void doDelete(String urlStr,Map<String,Object> paramMap) throws Exception{  
  103.         String paramStr = prepareParam(paramMap);  
  104.         if(paramStr == null || paramStr.trim().length()<1){  
  105.               
  106.         }else{  
  107.             urlStr +="?"+paramStr;  
  108.         }     
  109.         System.out.println(urlStr);  
  110.         URL url = new URL(urlStr);  
  111.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  112.         conn.setDoOutput(true);  
  113.         conn.setRequestMethod(SERVLET_DELETE);  
  114.         //屏蔽掉的代码是错误的,java.net.ProtocolException: HTTP method DELETE doesn't support output  
  115. /*      OutputStream os = conn.getOutputStream();      
  116.         os.write(paramStr.toString().getBytes("utf-8"));      
  117.         os.close();  */   
  118.           
  119.         if(conn.getResponseCode() ==200){  
  120.             System.out.println("成功");  
  121.         }else{  
  122.             System.out.println(conn.getResponseCode());  
  123.         }  
  124.     }  
  125.       
  126.     public static void main(String[] args) throws Exception{  
  127.         String urlStr = "http://localhost:8080/SwTest/ReceiveDataServlet";  
  128.         Map<String,Object> map = new HashMap<String,Object>();  
  129.         map.put("username","张三");  
  130.         map.put("password","88888");  
  131. //      URLConnectionUtil.doGet(urlStr, map);  
  132. //      URLConnectionUtil.doPost(urlStr, map);  
  133. //      URLConnectionUtil.doPut(urlStr, map);  
  134.         URLConnectionUtil.doDelete(urlStr, map);  
  135.           
  136.     }  
  137.       
  138.       
  139. }  

 

方法中是存在重复的。有些方法是可以通过参数的改变来达到统一,但是那样的做法对于程序的扩展性会有很大的局限性。

还是对于每一种方式提供一个单独的方法进行访问比较好。

在Servlet端,获取参数可以通过

request.getInputStream,及request.getParamter来进行。

其中,当Rest访问传入参数是通过conn的outputStream来进行的,可以通过request.getInputStream来进行参数获取(Post方式可通用);

当以url?key=value方法传递参数时,可以通过request.getParamter来进行参数获取。(Post方式可通用)

其中request.getInputStream和request.getParamter两种方式不能同时出现。当request.getParamter运行的过程,也是输入流的读取过程。当输入流读取完成后,再次调用时无效的。

附上Servlet端程序

  1. package  com.sw.servlet;  
  2.   
  3. import  java.io.BufferedReader;  
  4. import  java.io.IOException;  
  5. import  java.io.InputStreamReader;  
  6. import  java.io.OutputStream;  
  7.   
  8. import  javax.servlet.ServletException;  
  9. import  javax.servlet.ServletInputStream;  
  10. import  javax.servlet.http.HttpServlet;  
  11. import  javax.servlet.http.HttpServletRequest;  
  12. import  javax.servlet.http.HttpServletResponse;  
  13.   
  14. /**  
  15.  * Servlet implementation class ReceiveDataServlet  
  16.  */   
  17. public   class  ReceiveDataServlet  extends  HttpServlet {  
  18.     private   static   final   long  serialVersionUID = 1L;  
  19.          
  20.     /**  
  21.      * @see HttpServlet#HttpServlet()  
  22.      */   
  23.     public  ReceiveDataServlet() {  
  24.         super ();  
  25.         // TODO Auto-generated constructor stub   
  26.     }  
  27.   
  28.     /**  
  29.      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)  
  30.      */   
  31.     protected   void  doGet(HttpServletRequest request, HttpServletResponse response) throws  ServletException, IOException {  
  32.         System.out.println("----------get--------------" );        
  33.         String username = new  String(request.getParameter( "username" ).getBytes( "iso-8859-1" ), "utf-8" );  
  34.         String password = new  String(request.getParameter( "password" ).getBytes( "iso-8859-1" ), "utf-8" );  
  35.         System.out.println(username);  
  36.         System.out.println(password);  
  37.         OutputStream os = response.getOutputStream();  
  38.         os.write("get" .getBytes( "utf-8" ));  
  39.     }  
  40.   
  41.     /**  
  42.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
  43.      */   
  44.     protected   void  doPost(HttpServletRequest request, HttpServletResponse response) throws  ServletException, IOException {  
  45.         System.out.println("----------post--------------" );  
  46.         BufferedReader br = new  BufferedReader( new InputStreamReader((ServletInputStream)request.getInputStream()));  
  47.         String line = null ;  
  48.         StringBuilder sb = new  StringBuilder();  
  49.         while ((line = br.readLine())!= null ){  
  50.             sb.append(line);  
  51.         }         
  52.         System.out.println(sb.toString());  
  53.         br.close();  
  54. /*      String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");  
  55.         String password = new String(request.getParameter("password").getBytes("iso-8859-1"),"utf-8");  
  56.         System.out.println(username);  
  57.         System.out.println(password);  
  58. */       OutputStream os = response.getOutputStream();  
  59.         os.write("post" .getBytes( "utf-8" ));  
  60.     }  
  61.       
  62.     @Override   
  63.     protected   void doDelete(HttpServletRequest request, HttpServletResponse response)  
  64.             throws  ServletException, IOException {  
  65.         System.out.println("----------delete--------------" );  
  66.         String username = new  String(request.getParameter( "username" ).getBytes( "iso-8859-1" ), "utf-8" );  
  67.         String password = new  String(request.getParameter( "password" ).getBytes( "iso-8859-1" ), "utf-8" );  
  68.         System.out.println(username);  
  69.         System.out.println(password);  
  70.         OutputStream os = response.getOutputStream();  
  71.         os.write("delete" .getBytes( "utf-8" ));             
  72.     }  
  73.       
  74.     @Override   
  75.     protected   void  doPut(HttpServletRequest request, HttpServletResponse response)  
  76.             throws  ServletException, IOException {  
  77.         System.out.println("----------put--------------" );  
  78.           
  79.     /*  BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream())); 
  80.         String line = null;  
  81.         StringBuilder sb = new StringBuilder();  
  82.         while((line = br.readLine())!=null){  
  83.             sb.append(line);  
  84.         }         
  85.         System.out.println(sb.toString());  
  86.         br.close();*/   
  87.           
  88.         String username = new  String(request.getParameter( "username" ).getBytes( "iso-8859-1" ), "utf-8" );  
  89.         String password = new  String(request.getParameter( "password" ).getBytes( "iso-8859-1" ), "utf-8" );  
  90.         System.out.println(username);  
  91.         System.out.println(password);  
  92.         OutputStream os = response.getOutputStream();  
  93.         os.write("put" .getBytes( "utf-8" ));    
  94.     }  
  95.   
  96. }  

 

  1. package com.sw.servlet;  
  2. import java.io.BufferedReader;  
  3. import java.io.IOException;  
  4. import java.io.InputStreamReader;  
  5. import java.io.OutputStream;  
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.ServletInputStream;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. /** 
  12.  * Servlet implementation class ReceiveDataServlet 
  13.  */  
  14. public class ReceiveDataServlet extends HttpServlet {  
  15.     private static final long serialVersionUID = 1L;  
  16.          
  17.     /** 
  18.      * @see HttpServlet#HttpServlet() 
  19.      */  
  20.     public ReceiveDataServlet() {  
  21.         super();  
  22.         // TODO Auto-generated constructor stub  
  23.     }  
  24.     /** 
  25.      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
  26.      */  
  27.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  28.         System.out.println("----------get--------------");        
  29.         String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");  
  30.         String password = new String(request.getParameter("password").getBytes("iso-8859-1"),"utf-8");  
  31.         System.out.println(username);  
  32.         System.out.println(password);  
  33.         OutputStream os = response.getOutputStream();  
  34.         os.write("get".getBytes("utf-8"));  
  35.     }  
  36.     /** 
  37.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
  38.      */  
  39.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  40.         System.out.println("----------post--------------");  
  41.         BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));  
  42.         String line = null;  
  43.         StringBuilder sb = new StringBuilder();  
  44.         while((line = br.readLine())!=null){  
  45.             sb.append(line);  
  46.         }         
  47.         System.out.println(sb.toString());  
  48.         br.close();  
  49. /*      String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8"); 
  50.         String password = new String(request.getParameter("password").getBytes("iso-8859-1"),"utf-8"); 
  51.         System.out.println(username); 
  52.         System.out.println(password); 
  53. */      OutputStream os = response.getOutputStream();  
  54.         os.write("post".getBytes("utf-8"));  
  55.     }  
  56.       
  57.     @Override  
  58.     protected void doDelete(HttpServletRequest request, HttpServletResponse response)  
  59.             throws ServletException, IOException {  
  60.         System.out.println("----------delete--------------");  
  61.         String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");  
  62.         String password = new String(request.getParameter("password").getBytes("iso-8859-1"),"utf-8");  
  63.         System.out.println(username);  
  64.         System.out.println(password);  
  65.         OutputStream os = response.getOutputStream();  
  66.         os.write("delete".getBytes("utf-8"));             
  67.     }  
  68.       
  69.     @Override  
  70.     protected void doPut(HttpServletRequest request, HttpServletResponse response)  
  71.             throws ServletException, IOException {  
  72.         System.out.println("----------put--------------");  
  73.           
  74.     /*  BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream())); 
  75.         String line = null; 
  76.         StringBuilder sb = new StringBuilder(); 
  77.         while((line = br.readLine())!=null){ 
  78.             sb.append(line); 
  79.         }        
  80.         System.out.println(sb.toString()); 
  81.         br.close();*/  
  82.           
  83.         String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");  
  84.         String password = new String(request.getParameter("password").getBytes("iso-8859-1"),"utf-8");  
  85.         System.out.println(username);  
  86.         System.out.println(password);  
  87.         OutputStream os = response.getOutputStream();  
  88.         os.write("put".getBytes("utf-8"));    
  89.     }  
  90. }  

 

程序中对于request.getInputStream和getParameter的获取方式可能说明的会多少有些问题,我也是通过几组测试后得出的结论。肯定有我没有测试到得。如果有问题,请指出,我会再看到评论后进行测试,修改。

另外,Apache的HttpClient非常好。封装的详细。在我的工作中也用到过,在以后会对于HttpClient进行有些单独的程序笔记。

这里HttpUrlConnection是同事在别的项目中用到的,用法比较简单,我大体给他简单讲解了一下,简明扼要,功能完备,还是很方便,

所以在这里记下来,留个笔记吧。

btw,最近工作比较忙,有2个月没有写些东西了,在工作中确实还遇到了不少有意思的问题,最近刚好快闲下来了,慢慢整理一下。

posted @ 2012-08-18 10:47  GreyWolf  阅读(1078)  评论(0编辑  收藏  举报