在项目中,有时需要通过请求远程服务器上的url获取数据(前提是程序所在服务器可以和url服务器ping成功),
用java在后台发送请求时,用到了java.net.URL, java.net.URLConnection,
以下是分别用post和get方式请求url的简单工具类实现:
1 import java.io.BufferedReader; 2 import java.io.InputStreamReader; 3 import java.io.PrintWriter; 4 import java.net.URL; 5 import java.net.URLConnection; 6 import java.util.List; 7 import java.util.Map; 8 9 public class CallWebPage { 10 /** 11 * 用get方式连接url 12 * @param urlString url路径 13 * @param pdata url参数 14 * @return 从url获得的数据 15 */ 16 public static String CallWebPageGet(String urlString,String pdata) { 17 String result=""; 18 PrintWriter out = null; 19 BufferedReader in = null; 20 URL url=null; 21 try { 22 url = new URL(urlString+"?"+pdata);//用url路径以及所用参数创建URL实例类 23 URLConnection connect = url.openConnection();//创建连接 24 connect.setRequestProperty("content-type","application/x-www-form-urlencoded;charset=utf-8");//设置请求header的属性--请求内容类型 25 connect.setRequestProperty("method","GET");//设置请求header的属性值--请求方式 26 // 建立实际的连接 27 connect.connect(); //建立与url所在服务器的连接 28 // 获取所有响应头字段 29 Map<String, List<String>> map = connect.getHeaderFields(); 30 // 遍历所有的响应头字段 31 for (String key : map.keySet()) { 32 System.out.println(key + "--->" + map.get(key)); 33 } 34 // 定义BufferedReader输入流来读取URL的响应 35 in = new BufferedReader(new InputStreamReader(connect.getInputStream())); 36 String line=""; 37 while ((line = in.readLine()) != null) { 38 result += line; 39 } 40 } catch (Exception e) { 41 // TODO Auto-generated catch block 42 e.printStackTrace(); 43 } 44 45 return result; 46 } 47 /** 48 * 用gpost方式连接url 49 * @param urlString url路径 50 * @param pdata url参数 51 * @return 从url获得的数据 52 */ 53 public static String CallWebPagePost(String urlString,String pdata) { 54 String result=""; 55 PrintWriter out = null; 56 BufferedReader in = null; 57 URL url=null; 58 try { 59 url = new URL(urlString); 60 URLConnection connect = url.openConnection(); 61 connect.setRequestProperty("content-type","application/x-www-form-urlencoded;charset=utf-8"); 62 connect.setRequestProperty("method","POST"); 63 byte[] bytes= pdata.getBytes("utf-8") ; 64 connect.setDoOutput(true); 65 connect.setDoInput(true); 66 67 out = new PrintWriter(connect.getOutputStream()); 68 // 发送请求参数 69 out.print(pdata); 70 out.flush(); 71 // 定义BufferedReader输入流来读取URL的响应 72 in = new BufferedReader(new InputStreamReader(connect.getInputStream())); 73 String line; 74 while ((line = in.readLine()) != null) { 75 result += line; 76 } 77 } catch (Exception e) { 78 // TODO Auto-generated catch block 79 e.printStackTrace(); 80 } 81 82 return result; 83 } 84 }