使用Java发送GET、POST请求

本文提供了一个Java类示例,展示了如何通过GET和POST方法向指定URL发送请求并接收响应。该示例包括设置请求头、处理异常及正确关闭流资源等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值