`

HttpURLConnection简单用法

    博客分类:
  • java
阅读更多

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.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. } 

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

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

在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.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. } 

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

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

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

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

分享到:
评论

相关推荐

    java HttpURLConnection 使用示例

    本例子是 java 的 HttpURLConnection 使用方法,比较简单,但是涵盖了post和get两种方法,而且处理了乱码。

    java android httpURLConnection的封装

    针对httpURLConnection 的简单封装,简单易用,支持上传下载 用法自已研究吧、

    Android-HttpURLConnection:一款封装HttpURLConnection实现的简单的网络请求的事例

    Android-HttpURLConnection说明lib-http 后续不再...使用方法添加依赖在根目录添加发布插件的相关依赖buildscript { repositories { jcenter() } } allprojects { repositories { jcenter() } }importdependencies {

    TestHttpGet获取html获取网页get方法get网页get html demo java html post.7z

    4. 安卓系统下,AS IDE get post的使用方法,这个演示程序演示了如何用android java去访问网页,获取网页。 访问的是我的csdn主页,见程序中 streamToString getHtml HttpURLConnection conn = (HttpURLConnection) ...

    JAVA发送POST请求,如何使用JAVA发送POST请求

    如果您正在寻找一份JAVA客户端发送POST请求的示例代码...我们的示例代码非常简单易懂,适合初学者和有经验的用户使用。您可以根据自己的需求和场景,修改示例代码中的请求参数和响应处理方法,并将其应用到实际项目中。

    Android之封装好的异步网络请求框架

    Android中网络请求一般使用Apache HTTP Client或者采用HttpURLConnection,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使用这个MyHttpUtils库可以大大的简化操作,它是基于...

    使用Java动态代理实现一个简单的网络请求拦截器.txt

    这个代码实现了一个简单的网络请求拦截器,使用了Java的动态代理机制。在这个例子中,我们创建了一个`HttpRequestInterceptor`类来实现`InvocationHandler`接口,并在`invoke()`方法中实现了对目标方法的拦截操作。...

    AndroidVolley完全解析(一),初识Volley的基本用法

    不过HttpURLConnection和HttpClient的用法还是稍微有些复杂的,如果不进行适当封装的话,很容易就会写出不少重复代码。于是乎,一些Android网络通信框架也就应运而生,比如说AsyncHttpClient,它把HTTP所有的通信...

    Android Volley Jar框架 v2017.3.17.zip

    不过HttpURLConnection和HttpClient的用法还是稍微有些复杂的,如果不进行适当封装的话,很容易就会写出不少重复代码。于是乎,一些Android网络通信框架也就应运而生,比如说AsyncHttpClient,它把HTTP所有的通信...

    疯狂Android讲义源码

     13.3.1 使用HttpURLConnection 496  13.3.2 使用Apache HttpClient 501  13.4 使用WebView视图  显示网页 505  13.4.1 使用WebView浏览网页 506  13.4.2 使用WebView加载HTML  代码 507  13.5 使用Web ...

    疯狂Android讲义.part2

    13.3.1 使用HttpURLConnection 496 13.3.2 使用Apache HttpClient 501 13.4 使用WebView视图显示 网页 506 13.4.1 使用WebView浏览网页 506 13.4.2 使用WebView加载HTML 代码 507 13.5 使用Web Service进行网络 编程...

    疯狂Android讲义.part1

    13.3.1 使用HttpURLConnection 496 13.3.2 使用Apache HttpClient 501 13.4 使用WebView视图显示 网页 506 13.4.1 使用WebView浏览网页 506 13.4.2 使用WebView加载HTML 代码 507 13.5 使用Web Service进行网络 编程...

    iOS中使用NSURLConnection处理HTTP同步与异步请求

    NSURLConnection的作用现在已经基本被NSURLSession所取代,所以我们简单了解下iOS中使用NSURLConnection处理HTTP同步与异步请求的方法即可:

    android 常用工具类

    JSONUtils工具类,可用于方便的向Json中读取和写入相关类型数据,如: String getString(JSONObject jsonObject, String key, String default...更详细的设置 可以直接使用HttpURLConnection或apache的HttpClient。

    RestTemplate如何在Spring或非Spring环境下使用.docx

    RestTemplate是执行HTTP请求的同步阻塞式的客户端,它在HTTP客户端库(例如JDK HttpURLConnection,Apache HttpComponents,okHttp等)基础封装了更加简单易用的模板方法API。也就是说RestTemplate是一个封装,底层...

    安卓GET与POST网络请求的三种方式

    第一是比较原始的方法,使用HttpURLConnection, 第二是Volley框架, 第三是xutils3框架。 1.HttpURLConnection方法 这是基于网络通信HTTP协议的网络请求,其它两种框架也是基于HTTP协议的。HTTP协议是一款基于短...

    Android知识点及重要代码合集 word文档

    7.7使用runONUiThread()\HttpURLConnection完成文件下载操作 68 7.8 掌握AsyncTask异步任务下载网络资源 70 7.9 DatePickerDialog、TimePickerDialog的使用 76 8.1 ListView、SimpleAdapter和ArrayAdapter的使用 ...

Global site tag (gtag.js) - Google Analytics