Java网络技术整理(一)

引用:http://snowolf.iteye.com/blog/457905

做Java做了很多年,却总是把一些东西遗忘,过后再着急的找寻。最近,需要通过Java代码模拟一个表单提交,却怎么也想不起来如何封装数据了。在以前的代码里翻腾了好久,终于实验成功。索性,做一个了断! 放到博客中来!
本篇主要描述Java网络参数传递,主要分为get和post两种方式。
说句玩笑话,真有干了几年Java的朋友不知道get和post的差别,我就在这里唠叨几句。
1.Get方式
这种方式是最简单的参数传递方式。例如: http://www.zlex.org/get.do?a=3&b=5&c=7
这个url中,a、b和c是url参数,具体的说是参数名,与之用“=”隔开的是对应的参数值。也就是说参数a的值为3、参数b的值为5、参数c的值为7。get.do是请求地址,紧跟这个地址的参数a需要用“?”作为分隔符,其余参数用“&”做分隔符。
这种get请求发起后,服务器端可以通过request.getParameter()方法来获得参数值。如要获得参数a的值可以通过request.getParameter("a");
2.Post方式
相比get方式,post方式更为隐蔽。例如: http://www.zlex.org/post.do
在这个url中,你看不到任何参数,真正的参数隐藏在Http请求的数据体中。如果了解网络监听的话,就会对这一点深有体会。
我们举一个简单的例子:通过表单做登录操作。
我们简化一个登录表单:
Html代码   收藏代码
  1. <form action="login.do" method="post">  
  2. <ul>  
  3.     <li><label for="username">用户名</label><input id="username"  
  4.         name="username" type="text" /></li>  
  5.     <li><label for="password">密码</label><input id="password"  
  6.         type="password" /></li>  
  7.     <li><label><input type="submit" value="登录" /> <input  
  8.         type="reset" value="重置" /></label></li>  
  9. </ul>  
  10. </form>  

表单中有2个字段,用户名(username)和密码(password)
注意form标签中的method参数值是post!
即便是表单,在服务器端仍然可以通过request.getParameter()方法来获得参数值。
Post方式,其实是将表单字段和经过编码的字段值经过组合以数据体的方式做了参数传递。
经过一番阐述,相信大家对两种网络参数传递方式都有所了解了。
Get方式比较简单,通过构建一个简单HttpURLConnection就可以获得,我们暂且不说。
我们主要来描述一下如何通过java代码构建一个表单提交。
仔细研究表单提交时所对应的http数据体,发现其表单字段是以如下方式构建的:
Java代码   收藏代码
  1. arg0=urlencode(value0)&arg1=urlencode(value1)  

当然,尤其要注意字段名,参数名只不能使用中文这类字符。
作为表单, Content-Type也会有所不同,其值为 application/x-www-form-urlencoded以下做一个代码展示,以后再需要我就不用翻“旧账”了
我常用的网络工具,其功能远不止模拟一个post请求
Java代码   收藏代码
  1. /** 
  2.  * 2008-12-26 
  3.  */  
  4. package org.zlex.commons.net;  
  5.   
  6. import java.io.DataInputStream;  
  7. import java.io.DataOutputStream;  
  8. import java.io.UnsupportedEncodingException;  
  9. import java.net.HttpURLConnection;  
  10. import java.net.URL;  
  11. import java.net.URLDecoder;  
  12. import java.net.URLEncoder;  
  13. import java.util.Map;  
  14. import java.util.Properties;  
  15.   
  16. /** 
  17.  * 网络工具 
  18.  *  
  19.  * @author 梁栋 
  20.  * @version 1.0 
  21.  * @since 1.0 
  22.  */  
  23. public abstract class NetUtils {  
  24.     public static final String CHARACTER_ENCODING = "UTF-8";  
  25.     public static final String PATH_SIGN = "/";  
  26.     public static final String METHOD_POST = "POST";  
  27.     public static final String METHOD_GET = "GET";  
  28.     public static final String CONTENT_TYPE = "Content-Type";  
  29.   
  30.     /** 
  31.      * 以POST方式向指定地址发送数据包请求,并取得返回的数据包 
  32.      *  
  33.      * @param urlString 
  34.      * @param requestData 
  35.      * @return 返回数据包 
  36.      * @throws Exception 
  37.      */  
  38.     public static byte[] requestPost(String urlString, byte[] requestData)  
  39.             throws Exception {  
  40.         Properties requestProperties = new Properties();  
  41.         requestProperties.setProperty(CONTENT_TYPE,  
  42.                 "application/octet-stream; charset=utf-8");  
  43.   
  44.         return requestPost(urlString, requestData, requestProperties);  
  45.     }  
  46.   
  47.     /** 
  48.      * 以POST方式向指定地址发送数据包请求,并取得返回的数据包 
  49.      *  
  50.      * @param urlString 
  51.      * @param requestData 
  52.      * @param requestProperties 
  53.      * @return 返回数据包 
  54.      * @throws Exception 
  55.      */  
  56.     public static byte[] requestPost(String urlString, byte[] requestData,  
  57.             Properties requestProperties) throws Exception {  
  58.         byte[] responseData = null;  
  59.   
  60.         HttpURLConnection con = null;  
  61.   
  62.         try {  
  63.             URL url = new URL(urlString);  
  64.             con = (HttpURLConnection) url.openConnection();  
  65.   
  66.             if ((requestProperties != null) && (requestProperties.size() > 0)) {  
  67.                 for (Map.Entry<Object, Object> entry : requestProperties  
  68.                         .entrySet()) {  
  69.                     String key = String.valueOf(entry.getKey());  
  70.                     String value = String.valueOf(entry.getValue());  
  71.                     con.setRequestProperty(key, value);  
  72.                 }  
  73.             }  
  74.   
  75.             con.setRequestMethod(METHOD_POST); // 置为POST方法  
  76.   
  77.             con.setDoInput(true); // 开启输入流  
  78.             con.setDoOutput(true); // 开启输出流  
  79.   
  80.             // 如果请求数据不为空,输出该数据。  
  81.             if (requestData != null) {  
  82.                 DataOutputStream dos = new DataOutputStream(con  
  83.                         .getOutputStream());  
  84.                 dos.write(requestData);  
  85.                 dos.flush();  
  86.                 dos.close();  
  87.             }  
  88.   
  89.             int length = con.getContentLength();  
  90.             // 如果回复消息长度不为-1,读取该消息。  
  91.             if (length != -1) {  
  92.                 DataInputStream dis = new DataInputStream(con.getInputStream());  
  93.                 responseData = new byte[length];  
  94.                 dis.readFully(responseData);  
  95.                 dis.close();  
  96.             }  
  97.         } catch (Exception e) {  
  98.             throw e;  
  99.         } finally {  
  100.             if (con != null) {  
  101.                 con.disconnect();  
  102.                 con = null;  
  103.             }  
  104.         }  
  105.   
  106.         return responseData;  
  107.     }  
  108.   
  109.     /** 
  110.      * 以POST方式向指定地址提交表单<br> 
  111.      * arg0=urlencode(value0)&arg1=urlencode(value1) 
  112.      *  
  113.      * @param urlString 
  114.      * @param formProperties 
  115.      * @return 返回数据包 
  116.      * @throws Exception 
  117.      */  
  118.     public static byte[] requestPostForm(String urlString,  
  119.             Properties formProperties) throws Exception {  
  120.         Properties requestProperties = new Properties();  
  121.           
  122.         requestProperties.setProperty(CONTENT_TYPE,  
  123.                 "application/x-www-form-urlencoded");  
  124.           
  125.         return requestPostForm(urlString, formProperties, requestProperties);  
  126.     }  
  127.   
  128.     /** 
  129.      * 以POST方式向指定地址提交表单<br> 
  130.      * arg0=urlencode(value0)&arg1=urlencode(value1) 
  131.      *  
  132.      * @param urlString 
  133.      * @param formProperties 
  134.      * @param requestProperties 
  135.      * @return 返回数据包 
  136.      * @throws Exception 
  137.      */  
  138.     public static byte[] requestPostForm(String urlString,  
  139.             Properties formProperties, Properties requestProperties)  
  140.             throws Exception {  
  141.         StringBuilder sb = new StringBuilder();  
  142.   
  143.         if ((formProperties != null) && (formProperties.size() > 0)) {  
  144.             for (Map.Entry<Object, Object> entry : formProperties.entrySet()) {  
  145.                 String key = String.valueOf(entry.getKey());  
  146.                 String value = String.valueOf(entry.getValue());  
  147.                 sb.append(key);  
  148.                 sb.append("=");  
  149.                 sb.append(encode(value));  
  150.                 sb.append("&");  
  151.             }  
  152.         }  
  153.   
  154.         String str = sb.toString();  
  155.         str = str.substring(0, (str.length() - 1)); // 截掉末尾字符&  
  156.   
  157.         return requestPost(urlString, str.getBytes(CHARACTER_ENCODING),  
  158.                 requestProperties);  
  159.   
  160.     }  
  161.   
  162.     /** 
  163.      * url解码 
  164.      *  
  165.      * @param str 
  166.      * @return 解码后的字符串,当异常时返回原始字符串。 
  167.      */  
  168.     public static String decode(String url) {  
  169.         try {  
  170.             return URLDecoder.decode(url, CHARACTER_ENCODING);  
  171.         } catch (UnsupportedEncodingException ex) {  
  172.             return url;  
  173.         }  
  174.     }  
  175.   
  176.     /** 
  177.      * url编码 
  178.      *  
  179.      * @param str 
  180.      * @return 编码后的字符串,当异常时返回原始字符串。 
  181.      */  
  182.     public static String encode(String url) {  
  183.         try {  
  184.             return URLEncoder.encode(url, CHARACTER_ENCODING);  
  185.         } catch (UnsupportedEncodingException ex) {  
  186.             return url;  
  187.         }  
  188.     }  
  189. }  

注意上述requestPostForm()方法,是用来提交表单的。
测试用例
Java代码   收藏代码
  1. /** 
  2.  * 2009-8-21 
  3.  */  
  4. package org.zlex.commons.net;  
  5.   
  6. import static org.junit.Assert.*;  
  7.   
  8. import java.util.Properties;  
  9.   
  10. import org.junit.Test;  
  11.   
  12. /** 
  13.  * 网络工具测试 
  14.  *  
  15.  * @author 梁栋 
  16.  * @version 1.0 
  17.  * @since 1.0 
  18.  */  
  19. public class NetUtilsTest {  
  20.   
  21.     /** 
  22.      * Test method for 
  23.      * {@link org.zlex.commons.net.NetUtils#requestPost(java.lang.String, byte[])} 
  24.      * . 
  25.      */  
  26.     @Test  
  27.     public final void testRequestPostStringByteArray() throws Exception {  
  28.         Properties requestProperties = new Properties();  
  29.   
  30.         // 模拟浏览器信息  
  31.         requestProperties  
  32.                 .put(  
  33.                         "User-Agent",  
  34.                         "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; TencentTraveler ; .NET CLR 1.1.4322)");  
  35.   
  36.         byte[] b = NetUtils.requestPost("http://localhost:8080/zlex/post.do",  
  37.                 "XML".getBytes());  
  38.         System.err.println(new String(b, "utf-8"));  
  39.     }  
  40.   
  41.     /** 
  42.      * Test method for 
  43.      * {@link org.zlex.commons.net.NetUtils#requestPostForm(java.lang.String, java.util.Properties)} 
  44.      * . 
  45.      */  
  46.     @Test  
  47.     public final void testRequestPostForm() throws Exception {  
  48.         Properties formProperties = new Properties();  
  49.   
  50.         formProperties.put("j_username""Admin");  
  51.         formProperties.put("j_password""manage");  
  52.   
  53.         byte[] b = NetUtils.requestPostForm(  
  54.                 "http://localhost:8080/zlex/j_spring_security_check",  
  55.                 formProperties);  
  56.         System.err.println(new String(b, "utf-8"));  
  57.     }  
  58. }  

测试用例中的第二个方法是我用来测试SpringSecurity的登录操作,结果是可行的! 做Java做了很多年,却总是把一些东西遗忘,过后再着急的找寻。最近,需要通过Java代码模拟一个表单提交,却怎么也想不起来如何封装数据了。在以前的代码里翻腾了好久,终于实验成功。索性,做一个了断! 放到博客中来!
本篇主要描述Java网络参数传递,主要分为get和post两种方式。
说句玩笑话,真有干了几年Java的朋友不知道get和post的差别,我就在这里唠叨几句。
1.Get方式
这种方式是最简单的参数传递方式。例如: http://www.zlex.org/get.do?a=3&b=5&c=7
这个url中,a、b和c是url参数,具体的说是参数名,与之用“=”隔开的是对应的参数值。也就是说参数a的值为3、参数b的值为5、参数c的值为7。get.do是请求地址,紧跟这个地址的参数a需要用“?”作为分隔符,其余参数用“&”做分隔符。
这种get请求发起后,服务器端可以通过request.getParameter()方法来获得参数值。如要获得参数a的值可以通过request.getParameter("a");
2.Post方式
相比get方式,post方式更为隐蔽。例如: http://www.zlex.org/post.do
在这个url中,你看不到任何参数,真正的参数隐藏在Http请求的数据体中。如果了解网络监听的话,就会对这一点深有体会。
我们举一个简单的例子:通过表单做登录操作。
我们简化一个登录表单:
Html代码   收藏代码
  1. <form action="login.do" method="post">  
  2. <ul>  
  3.     <li><label for="username">用户名</label><input id="username"  
  4.         name="username" type="text" /></li>  
  5.     <li><label for="password">密码</label><input id="password"  
  6.         type="password" /></li>  
  7.     <li><label><input type="submit" value="登录" /> <input  
  8.         type="reset" value="重置" /></label></li>  
  9. </ul>  
  10. </form>  

表单中有2个字段,用户名(username)和密码(password)
注意form标签中的method参数值是post!
即便是表单,在服务器端仍然可以通过request.getParameter()方法来获得参数值。
Post方式,其实是将表单字段和经过编码的字段值经过组合以数据体的方式做了参数传递。
经过一番阐述,相信大家对两种网络参数传递方式都有所了解了。
Get方式比较简单,通过构建一个简单HttpURLConnection就可以获得,我们暂且不说。
我们主要来描述一下如何通过java代码构建一个表单提交。
仔细研究表单提交时所对应的http数据体,发现其表单字段是以如下方式构建的:
Java代码   收藏代码
  1. arg0=urlencode(value0)&arg1=urlencode(value1)  

当然,尤其要注意字段名,参数名只不能使用中文这类字符。
作为表单, Content-Type也会有所不同,其值为 application/x-www-form-urlencoded以下做一个代码展示,以后再需要我就不用翻“旧账”了
我常用的网络工具,其功能远不止模拟一个post请求
Java代码   收藏代码
  1. /** 
  2.  * 2008-12-26 
  3.  */  
  4. package org.zlex.commons.net;  
  5.   
  6. import java.io.DataInputStream;  
  7. import java.io.DataOutputStream;  
  8. import java.io.UnsupportedEncodingException;  
  9. import java.net.HttpURLConnection;  
  10. import java.net.URL;  
  11. import java.net.URLDecoder;  
  12. import java.net.URLEncoder;  
  13. import java.util.Map;  
  14. import java.util.Properties;  
  15.   
  16. /** 
  17.  * 网络工具 
  18.  *  
  19.  * @author 梁栋 
  20.  * @version 1.0 
  21.  * @since 1.0 
  22.  */  
  23. public abstract class NetUtils {  
  24.     public static final String CHARACTER_ENCODING = "UTF-8";  
  25.     public static final String PATH_SIGN = "/";  
  26.     public static final String METHOD_POST = "POST";  
  27.     public static final String METHOD_GET = "GET";  
  28.     public static final String CONTENT_TYPE = "Content-Type";  
  29.   
  30.     /** 
  31.      * 以POST方式向指定地址发送数据包请求,并取得返回的数据包 
  32.      *  
  33.      * @param urlString 
  34.      * @param requestData 
  35.      * @return 返回数据包 
  36.      * @throws Exception 
  37.      */  
  38.     public static byte[] requestPost(String urlString, byte[] requestData)  
  39.             throws Exception {  
  40.         Properties requestProperties = new Properties();  
  41.         requestProperties.setProperty(CONTENT_TYPE,  
  42.                 "application/octet-stream; charset=utf-8");  
  43.   
  44.         return requestPost(urlString, requestData, requestProperties);  
  45.     }  
  46.   
  47.     /** 
  48.      * 以POST方式向指定地址发送数据包请求,并取得返回的数据包 
  49.      *  
  50.      * @param urlString 
  51.      * @param requestData 
  52.      * @param requestProperties 
  53.      * @return 返回数据包 
  54.      * @throws Exception 
  55.      */  
  56.     public static byte[] requestPost(String urlString, byte[] requestData,  
  57.             Properties requestProperties) throws Exception {  
  58.         byte[] responseData = null;  
  59.   
  60.         HttpURLConnection con = null;  
  61.   
  62.         try {  
  63.             URL url = new URL(urlString);  
  64.             con = (HttpURLConnection) url.openConnection();  
  65.   
  66.             if ((requestProperties != null) && (requestProperties.size() > 0)) {  
  67.                 for (Map.Entry<Object, Object> entry : requestProperties  
  68.                         .entrySet()) {  
  69.                     String key = String.valueOf(entry.getKey());  
  70.                     String value = String.valueOf(entry.getValue());  
  71.                     con.setRequestProperty(key, value);  
  72.                 }  
  73.             }  
  74.   
  75.             con.setRequestMethod(METHOD_POST); // 置为POST方法  
  76.   
  77.             con.setDoInput(true); // 开启输入流  
  78.             con.setDoOutput(true); // 开启输出流  
  79.   
  80.             // 如果请求数据不为空,输出该数据。  
  81.             if (requestData != null) {  
  82.                 DataOutputStream dos = new DataOutputStream(con  
  83.                         .getOutputStream());  
  84.                 dos.write(requestData);  
  85.                 dos.flush();  
  86.                 dos.close();  
  87.             }  
  88.   
  89.             int length = con.getContentLength();  
  90.             // 如果回复消息长度不为-1,读取该消息。  
  91.             if (length != -1) {  
  92.                 DataInputStream dis = new DataInputStream(con.getInputStream());  
  93.                 responseData = new byte[length];  
  94.                 dis.readFully(responseData);  
  95.                 dis.close();  
  96.             }  
  97.         } catch (Exception e) {  
  98.             throw e;  
  99.         } finally {  
  100.             if (con != null) {  
  101.                 con.disconnect();  
  102.                 con = null;  
  103.             }  
  104.         }  
  105.   
  106.         return responseData;  
  107.     }  
  108.   
  109.     /** 
  110.      * 以POST方式向指定地址提交表单<br> 
  111.      * arg0=urlencode(value0)&arg1=urlencode(value1) 
  112.      *  
  113.      * @param urlString 
  114.      * @param formProperties 
  115.      * @return 返回数据包 
  116.      * @throws Exception 
  117.      */  
  118.     public static byte[] requestPostForm(String urlString,  
  119.             Properties formProperties) throws Exception {  
  120.         Properties requestProperties = new Properties();  
  121.           
  122.         requestProperties.setProperty(CONTENT_TYPE,  
  123.                 "application/x-www-form-urlencoded");  
  124.           
  125.         return requestPostForm(urlString, formProperties, requestProperties);  
  126.     }  
  127.   
  128.     /** 
  129.      * 以POST方式向指定地址提交表单<br> 
  130.      * arg0=urlencode(value0)&arg1=urlencode(value1) 
  131.      *  
  132.      * @param urlString 
  133.      * @param formProperties 
  134.      * @param requestProperties 
  135.      * @return 返回数据包 
  136.      * @throws Exception 
  137.      */  
  138.     public static byte[] requestPostForm(String urlString,  
  139.             Properties formProperties, Properties requestProperties)  
  140.             throws Exception {  
  141.         StringBuilder sb = new StringBuilder();  
  142.   
  143.         if ((formProperties != null) && (formProperties.size() > 0)) {  
  144.             for (Map.Entry<Object, Object> entry : formProperties.entrySet()) {  
  145.                 String key = String.valueOf(entry.getKey());  
  146.                 String value = String.valueOf(entry.getValue());  
  147.                 sb.append(key);  
  148.                 sb.append("=");  
  149.                 sb.append(encode(value));  
  150.                 sb.append("&");  
  151.             }  
  152.         }  
  153.   
  154.         String str = sb.toString();  
  155.         str = str.substring(0, (str.length() - 1)); // 截掉末尾字符&  
  156.   
  157.         return requestPost(urlString, str.getBytes(CHARACTER_ENCODING),  
  158.                 requestProperties);  
  159.   
  160.     }  
  161.   
  162.     /** 
  163.      * url解码 
  164.      *  
  165.      * @param str 
  166.      * @return 解码后的字符串,当异常时返回原始字符串。 
  167.      */  
  168.     public static String decode(String url) {  
  169.         try {  
  170.             return URLDecoder.decode(url, CHARACTER_ENCODING);  
  171.         } catch (UnsupportedEncodingException ex) {  
  172.             return url;  
  173.         }  
  174.     }  
  175.   
  176.     /** 
  177.      * url编码 
  178.      *  
  179.      * @param str 
  180.      * @return 编码后的字符串,当异常时返回原始字符串。 
  181.      */  
  182.     public static String encode(String url) {  
  183.         try {  
  184.             return URLEncoder.encode(url, CHARACTER_ENCODING);  
  185.         } catch (UnsupportedEncodingException ex) {  
  186.             return url;  
  187.         }  
  188.     }  
  189. }  

注意上述requestPostForm()方法,是用来提交表单的。
测试用例
Java代码   收藏代码
  1. /** 
  2.  * 2009-8-21 
  3.  */  
  4. package org.zlex.commons.net;  
  5.   
  6. import static org.junit.Assert.*;  
  7.   
  8. import java.util.Properties;  
  9.   
  10. import org.junit.Test;  
  11.   
  12. /** 
  13.  * 网络工具测试 
  14.  *  
  15.  * @author 梁栋 
  16.  * @version 1.0 
  17.  * @since 1.0 
  18.  */  
  19. public class NetUtilsTest {  
  20.   
  21.     /** 
  22.      * Test method for 
  23.      * {@link org.zlex.commons.net.NetUtils#requestPost(java.lang.String, byte[])} 
  24.      * . 
  25.      */  
  26.     @Test  
  27.     public final void testRequestPostStringByteArray() throws Exception {  
  28.         Properties requestProperties = new Properties();  
  29.   
  30.         // 模拟浏览器信息  
  31.         requestProperties  
  32.                 .put(  
  33.                         "User-Agent",  
  34.                         "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; TencentTraveler ; .NET CLR 1.1.4322)");  
  35.   
  36.         byte[] b = NetUtils.requestPost("http://localhost:8080/zlex/post.do",  
  37.                 "XML".getBytes());  
  38.         System.err.println(new String(b, "utf-8"));  
  39.     }  
  40.   
  41.     /** 
  42.      * Test method for 
  43.      * {@link org.zlex.commons.net.NetUtils#requestPostForm(java.lang.String, java.util.Properties)} 
  44.      * . 
  45.      */  
  46.     @Test  
  47.     public final void testRequestPostForm() throws Exception {  
  48.         Properties formProperties = new Properties();  
  49.   
  50.         formProperties.put("j_username""Admin");  
  51.         formProperties.put("j_password""manage");  
  52.   
  53.         byte[] b = NetUtils.requestPostForm(  
  54.                 "http://localhost:8080/zlex/j_spring_security_check",  
  55.                 formProperties);  
  56.         System.err.println(new String(b, "utf-8"));  
  57.     }  
  58. }  

测试用例中的第二个方法是我用来测试SpringSecurity的登录操作,结果是可行的!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值