使用Java发送GET、POST请求

来源:互联网 发布:php blog 系统 编辑:程序博客网 时间:2024/04/29 22:33
    ——节选自《疯狂Java讲义》 
    URL的openConnection()方法将返回一个URLConnection对象,该对象表示应用程序和 URL 之间的通信链接。程序可以通过URLConnection实例向该URL发送请求、读取URL引用的资源。 
    通常创建一个和 URL 的连接,并发送请求、读取此 URL 引用的资源需要如下几个步骤: 
    (1)通过调用URL对象openConnection()方法来创建URLConnection对象。 
    (2)设置URLConnection的参数和普通请求属性。 
    (3)如果只是发送GET方式请求,使用connect方法建立和远程资源之间的实际连接即可;如果需要发送POST方式的请求,需要获取URLConnection实例对应的输出流来发送请求参数。 
    (4)远程资源变为可用,程序可以访问远程资源的头字段、或通过输入流读取远程资源的数据。
Java代码  收藏代码
  1. public class TestGetPost {  
  2.     /** 
  3.      * 向指定URL发送GET方法的请求 
  4.      * @param url  发送请求的URL 
  5.      * @param param  请求参数,请求参数应该是name1=value1&name2=value2的形式 
  6.      * @return URL所代表远程资源的响应 
  7.      */  
  8.   
  9.     public static String sendGet(String url, String param) {  
  10.         String result = "";  
  11.         BufferedReader in = null;  
  12.         try {  
  13.             String urlName = url + "?" + param;  
  14.             URL realUrl = new URL(urlName);  
  15.             // 打开和URL之间的连接  
  16.             URLConnection conn = realUrl.openConnection();  
  17.             // 设置通用的请求属性  
  18.             conn.setRequestProperty("accept""*/*");  
  19.             conn.setRequestProperty("connection""Keep-Alive");  
  20.             conn.setRequestProperty("user-agent""Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");  
  21.             // 建立实际的连接  
  22.             conn.connect();  
  23.             // 获取所有响应头字段  
  24.                                 Map<String, List<String>> map = conn.getHeaderFields();  
  25.             // 遍历所有的响应头字段  
  26.             for (String key : map.keySet()) {  
  27.                 System.out.println(key + "--->" + map.get(key));  
  28.             }  
  29.             // 定义BufferedReader输入流来读取URL的响应  
  30.             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  31.             String line;  
  32.             while ((line = in.readLine()) != null) {  
  33.                 result += "\n" + line;  
  34.             }  
  35.         } catch (Exception e) {  
  36.             System.out.println("发送GET请求出现异常!" + e);  
  37.             e.printStackTrace();  
  38.         }  
  39.         // 使用finally块来关闭输入流  
  40.         finally {  
  41.             try {  
  42.                 if (in != null) {  
  43.                     in.close();  
  44.                 }  
  45.             } catch (IOException ex) {  
  46.                 ex.printStackTrace();  
  47.             }  
  48.         }  
  49.         return result;  
  50.     }  
  51.   
  52. /**  
  53.      * 向指定URL发送POST方法的请求  
  54.      * @param url 发送请求的URL  
  55.      * @param param 请求参数,请求参数应该是name1=value1&name2=value2的形式  
  56.      * @return URL所代表远程资源的响应  
  57.      */  
  58.     public static String sendPost(String url, String param) {  
  59.         PrintWriter out = null;  
  60.         BufferedReader in = null;  
  61.         String result = "";  
  62.         try {  
  63.             URL realUrl = new URL(url);  
  64.             // 打开和URL之间的连接  
  65.             URLConnection conn = realUrl.openConnection();  
  66.             // 设置通用的请求属性  
  67.             conn.setRequestProperty("accept""*/*");  
  68.             conn.setRequestProperty("connection""Keep-Alive");  
  69.             conn.setRequestProperty("user-agent""Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");  
  70.               
  71.             conn.setDoOutput(true);// 发送POST请求必须设置如下两行  
  72.             conn.setDoInput(true);  
  73.               
  74.             out = new PrintWriter(conn.getOutputStream());// 获取URLConnection对象对应的输出流s  
  75.             out.print(param);// 发送请求参数  
  76.             out.flush();// flush输出流的缓冲  
  77.             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));// 定义BufferedReader输入流来读取URL的响应  
  78.             String line;  
  79.             while ((line = in.readLine()) != null) {  
  80.                 result += "\n" + line;  
  81.             }  
  82.         } catch (Exception e) {  
  83.             System.out.println("发送POST请求出现异常!" + e);  
  84.             e.printStackTrace();  
  85.         }  
  86.         // 使用finally块来关闭输出流、输入流  
  87.         finally {  
  88.             try {  
  89.                 if (out != null) {  
  90.                     out.close();  
  91.                 }  
  92.                 if (in != null) {  
  93.                     in.close();  
  94.                 }  
  95.             } catch (IOException ex) {  
  96.                 ex.printStackTrace();  
  97.             }  
  98.         }  
  99.         return result;  
  100.     }  
  101.   
  102.     // 提供主方法,测试发送GET请求和POST请求  
  103.     public static void main(String args[]) {  
  104.         // 发送GET请求  
  105. //      String s = TestGetPost.sendGet("http://localhost:8080/xtest/URLresponse.jsp", "msg=888");  
  106. //      System.out.println(s);  
  107.         // 发送POST请求  
  108.         String s1 = TestGetPost.sendPost("http://localhost:8080/xtest/URLresponse.jsp""user=李刚&pass=abc");  
  109.         System.out.println(s1);  
  110.     }  
  111. }  
0 0
原创粉丝点击