Java 使用 URLConnection 模拟 Http Get和Post 提交

1、URLConnectionHelper

001 package com.hcm.rulconnetion.utils;
002  
003 import java.io.BufferedReader;
004 import java.io.IOException;
005 import java.io.InputStreamReader;
006 import java.io.PrintWriter;
007 import java.net.URL;
008 import java.net.URLConnection;
009 import java.util.List;
010 import java.util.Map;
011  
012 public class URLConnectionHelper {
013  
014     /**
015      * 向指定URL发送GET方法的请求
016      *
017      * @param url
018      *            发送请求的URL
019      * @param params
020      *            请求参数,请求参数应该是name1=value1&name2=value2的形式。
021      * @return URL所代表远程资源的响应
022      */
023     public static String sendGet(String url, String params) {
024         String result = "";
025         BufferedReader in = null;
026         try {
027             String urlName = url + "?" + params;
028             URL realUrl = new URL(urlName);
029             // 打开和URL之间的连接
030             URLConnection conn = realUrl.openConnection();
031             // 设置通用的请求属性
032             conn.setRequestProperty("accept", "*/*");
033             conn.setRequestProperty("connection", "Keep-Alive");
034             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
035  
036             // 建立实际的连接
037             conn.connect();
038             // 获取所有响应头字段
039  
040             Map<String, List<String>> map = conn.getHeaderFields();
041             // 遍历所有的响应头字段
042             for (String key : map.keySet()) {
043                 System.out.println(key + "--->" + map.get(key));
044             }
045  
046             // 定义BufferedReader输入流来读取URL的响应
047             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
048             String line;
049             while ((line = in.readLine()) != null) {
050                 result += "\n" + line;
051             }
052         } catch (Exception e) {
053             System.out.println("发送GET请求出现异常!" + e);
054             e.printStackTrace();
055         }
056         // 使用finally块来关闭输入流
057         finally {
058             try {
059                 if (in != null) {
060                     in.close();
061                 }
062             } catch (IOException ex) {
063                 ex.printStackTrace();
064             }
065         }
066         return result;
067     }
068  
069     /**
070      * 向指定URL发送POST方法的请求
071      *
072      * @param url
073      *            发送请求的URL
074      * @param params
075      *            请求参数,请求参数应该是name1=value1&name2=value2的形式。
076      * @return URL所代表远程资源的响应
077      */
078     public static String sendPost(String url, String params) {
079         PrintWriter out = null;
080         BufferedReader in = null;
081         String result = "";
082         try {
083             URL realUrl = new URL(url);
084             // 打开和URL之间的连接
085             URLConnection conn = realUrl.openConnection();
086             // 设置通用的请求属性
087             conn.setRequestProperty("accept", "*/*");
088             conn.setRequestProperty("connection", "Keep-Alive");
089             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
090  
091             // 发送POST请求必须设置如下两行
092             conn.setDoOutput(true);
093             conn.setDoInput(true);
094             // 获取URLConnection对象对应的输出流
095             out = new PrintWriter(conn.getOutputStream());
096             // 发送请求参数
097             out.print(params);
098             // flush输出流的缓冲
099             out.flush();
100  
101             // 定义BufferedReader输入流来读取URL的响应
102             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
103             String line;
104             while ((line = in.readLine()) != null) {
105                 result += "\n" + line;
106             }
107         } catch (Exception e) {
108             System.out.println("发送POST请求出现异常!" + e);
109             e.printStackTrace();
110         }
111         // 使用finally块来关闭输出流、输入流
112         finally {
113             try {
114                 if (out != null) {
115                     out.close();
116                 }
117                 if (in != null) {
118                     in.close();
119                 }
120             } catch (IOException ex) {
121                 ex.printStackTrace();
122             }
123         }
124         return result;
125     }
126 }

2、测试sendGet方法

1 @Test
2 public void testSendGet<span></span>() {
3     String url = "http://127.0.0.1:8086/web_test/a.jsp";
4     String str = URLConnectionHelper.sendGet(url, null);
5     System.out.println(str);
6 }

3、测试sendPost方法

1 @Test
2 public void testSendPost() {
3     String url = "http://127.0.0.1:8086/web_test/UserLoginServlet";
4     String params = "username=admin&password=123456";
5     String str = URLConnectionHelper.sendPost(url, params);
6     System.out.println(str);
7

}

你可能感兴趣的:(urlconnection)