发新话题
打印

HttpURLConnection简单用法

HttpURLConnection简单用法

HttpURLConnection为javaAPI提供的一种Rest访问的方式。其支持对Post,Delete,Get,Put等方式的访问。
以下为关于HttpURLConnection对Post等方式访问的一段代码。
view plaincopy to clipboardprint?
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.HttpURLConnection;  7. import java.URL;  8. import java.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(MapString,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,MapString,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,MapString,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,MapString,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,MapString,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.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 = "localhost:8080/SwTest/ReceiveDataServlet"; 130. MapString,Object map = new HashMapString,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. }
方法中是存在重复的。有些方法是可以经过参数的改动来到达一致,但是那样的做法关于顺序的扩展性会有很大的局限性。
还是关于每一种方式提供一个单独的方法停止访问比较好。
在Servlet端,获取参数可以经过
request.getInputStream,及request.getParamter来停止。
其中,当Rest访问传入参数是经过conn的outputStream来停止的,可以经过request.getInputStream来停止参数获取(Post方式可通用);
当以url?key=value方法传递参数时,可以经过request.getParamter来停止参数获取。(Post方式可通用)
其中request.getInputStream和request.getParamter两种方式不能同时呈现。当request.getParamter运转的过程,也是输入流的读取过程。当输入流读取完成后,再次调用时无效的。
附上Servlet端顺序
view plaincopy to clipboardprint?
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.ploverprintln(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. }
顺序中关于request.getInputStream和getParameter的获取方式能够说明的会多少有些成绩,我也是经过几组测试后得出的结论。一定有我没有测试到得。假如有成绩,请指出,我会再看到评论后停止测试,修正。
另外,Apache的HttpClient十分好。封装的详细。在我的工作中也用到过,在以后会关于HttpClient停止有些单独的顺序笔记。
这里HttpUrlConnection是同事在别的项目中用到的,用法比较简单,我大体给他简单讲解了一下,长篇大论,功用完备,还是很方便,
所以在这里记下来,留个笔记吧。
btw,最近工作比较忙,有2个月没有写些东西了,在工作中确实还遇到了不少有意思的成绩,最近刚好快闲下来了,慢慢整理一下。
jiyizhen-buy.com颈椎保健枕太空记忆枕 igerl.com歌瑞尔内衣

TOP

发新话题