守望者--AIR技术交流

标题: 使用Java发送GET、POST请求 [打印本页]

作者: 破晓    时间: 2015-7-27 09:05
标题: 使用Java发送GET、POST请求
FLSAH 开发过程中经常遇到访问别人的WEB服务遇到安全沙箱问题,而又不能强制要求别人放安全策略文件,那么我们可以从后台作为中转,访问服务

  1. public class TestGetPost {
  2.         /**
  3.          * 向指定URL发送GET方法的请求
  4.          * @param url  发送请求的URL
  5.          * @param param  请求参数,请求参数应该是name1=value1&name2=value2的形式
  6.          * @return URL所代表远程资源的响应
  7.          */

  8.         public static String sendGet(String url, String param) {
  9.                 String result = "";
  10.                 BufferedReader in = null;
  11.                 try {
  12.                         String urlName = url + "?" + param;
  13.                         URL realUrl = new URL(urlName);
  14.                         // 打开和URL之间的连接
  15.                         URLConnection conn = realUrl.openConnection();
  16.                         // 设置通用的请求属性
  17.                         conn.setRequestProperty("accept", "*/*");
  18.                         conn.setRequestProperty("connection", "Keep-Alive");
  19.                         conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
  20.                         // 建立实际的连接
  21.                         conn.connect();
  22.                         // 获取所有响应头字段
  23.                                 Map<String, List<String>> map = conn.getHeaderFields();
  24.                         // 遍历所有的响应头字段
  25.                         for (String key : map.keySet()) {
  26.                                 System.out.println(key + "--->" + map.get(key));
  27.                         }
  28.                         // 定义BufferedReader输入流来读取URL的响应
  29.                         in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  30.                         String line;
  31.                         while ((line = in.readLine()) != null) {
  32.                                 result += "\n" + line;
  33.                         }
  34.                 } catch (Exception e) {
  35.                         System.out.println("发送GET请求出现异常!" + e);
  36.                         e.printStackTrace();
  37.                 }
  38.                 // 使用finally块来关闭输入流
  39.                 finally {
  40.                         try {
  41.                                 if (in != null) {
  42.                                         in.close();
  43.                                 }
  44.                         } catch (IOException ex) {
  45.                                 ex.printStackTrace();
  46.                         }
  47.                 }
  48.                 return result;
  49.         }

  50. /**
  51.          * 向指定URL发送POST方法的请求
  52.          * @param url 发送请求的URL
  53.          * @param param 请求参数,请求参数应该是name1=value1&name2=value2的形式
  54.          * @return URL所代表远程资源的响应
  55.          */
  56.         public static String sendPost(String url, String param) {
  57.                 PrintWriter out = null;
  58.                 BufferedReader in = null;
  59.                 String result = "";
  60.                 try {
  61.                         URL realUrl = new URL(url);
  62.                         // 打开和URL之间的连接
  63.                         URLConnection conn = realUrl.openConnection();
  64.                         // 设置通用的请求属性
  65.                         conn.setRequestProperty("accept", "*/*");
  66.                         conn.setRequestProperty("connection", "Keep-Alive");
  67.                         conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
  68.                        
  69.                         conn.setDoOutput(true);// 发送POST请求必须设置如下两行
  70.                         conn.setDoInput(true);
  71.                        
  72.                         out = new PrintWriter(conn.getOutputStream());// 获取URLConnection对象对应的输出流s
  73.                         out.print(param);// 发送请求参数
  74.                         out.flush();// flush输出流的缓冲
  75.                         in = new BufferedReader(new InputStreamReader(conn.getInputStream()));// 定义BufferedReader输入流来读取URL的响应
  76.                         String line;
  77.                         while ((line = in.readLine()) != null) {
  78.                                 result += "\n" + line;
  79.                         }
  80.                 } catch (Exception e) {
  81.                         System.out.println("发送POST请求出现异常!" + e);
  82.                         e.printStackTrace();
  83.                 }
  84.                 // 使用finally块来关闭输出流、输入流
  85.                 finally {
  86.                         try {
  87.                                 if (out != null) {
  88.                                         out.close();
  89.                                 }
  90.                                 if (in != null) {
  91.                                         in.close();
  92.                                 }
  93.                         } catch (IOException ex) {
  94.                                 ex.printStackTrace();
  95.                         }
  96.                 }
  97.                 return result;
  98.         }

  99.         // 提供主方法,测试发送GET请求和POST请求
  100.         public static void main(String args[]) {
  101.                 // 发送GET请求
  102. //                String s = TestGetPost.sendGet("http://localhost:8080/xtest/URLresponse.jsp", "msg=888");
  103. //                System.out.println(s);
  104.                 // 发送POST请求
  105.                 String s1 = TestGetPost.sendPost("http://localhost:8080/xtest/URLresponse.jsp",        "user=李刚&pass=abc");
  106.                 System.out.println(s1);
  107.         }
  108. }
复制代码




例子:访问百度apistore  接口:

  1. package com.service;

  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import java.net.URL;
  5. import java.net.URLConnection;


  6. public class BaiduAPIService {
  7.         private static String APIKEY = "e5844ee56d2dc758e93551b0053be824";
  8.         private static String SERVICE_URL = "http://apis.baidu.com/apistore/";
  9.        
  10.        
  11.         /**
  12.      * 向指定URL发送GET方法的请求
  13.      * @param url  发送请求的URL
  14.      * @param param  请求参数,请求参数应该是name1=value1&name2=value2的形式
  15.      * @return URL所代表远程资源的响应
  16.      */  
  17.   
  18.     public static String sendGet(String url) {  
  19.         String result = "";  
  20.         BufferedReader in = null;  
  21.         try {  
  22.             String urlName = SERVICE_URL + url;  
  23.             URL realUrl = new URL(urlName);  
  24.             // 打开和URL之间的连接  
  25.             URLConnection conn = realUrl.openConnection();  
  26.             // 设置通用的请求属性  
  27.             conn.setRequestProperty("apikey", APIKEY);  
  28.             // 建立实际的连接  
  29.             conn.connect();  
  30.               
  31.             // 定义BufferedReader输入流来读取URL的响应  
  32.             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  33.             String line;  
  34.             while ((line = in.readLine()) != null) {  
  35.                 result +=  line;  
  36.             }  
  37.         } catch (Exception e) {  
  38.             System.out.println("发送GET请求出现异常!" + e);  
  39.             e.printStackTrace();  
  40.         }  
  41.         // 使用finally块来关闭输入流  
  42.         finally {  
  43.             try {  
  44.                 if (in != null) {  
  45.                     in.close();  
  46.                 }  
  47.             } catch (Exception ex) {  
  48.                 ex.printStackTrace();  
  49.             }  
  50.         }  
  51.         return result;  
  52.     }  
  53. }
复制代码



参考资料:http://well-lf.iteye.com/blog/982042





欢迎光临 守望者--AIR技术交流 (http://www.airmyth.com/)