java 模拟HTTP doPost请求 设置参数

  1. 请求模拟 
  2. package org.zlex.commons.net;    
  3.    
  4. import java.io.DataInputStream;    
  5. import java.io.DataOutputStream;
  6. import java.io.UnsupportedEncodingException;    
  7. import java.net.HttpURLConnection;    
  8. import java.net.URL;    
  9. import java.net.URLDecoder;    
  10. import java.net.URLEncoder;    
  11. import java.util.Map;    
  12. import java.util.Properties;    
  13.    
  14. /** 
  15. * 网络工具 
  16. *  
  17. * @author 梁栋 
  18. * @version 1.0 
  19. * @since 1.0 
  20. */   
  21. public abstract class NetUtils {    
  22.     public static final String CHARACTER_ENCODING = "UTF-8";    
  23.     public static final String PATH_SIGN = "/";    
  24.     public static final String METHOD_POST = "POST";    
  25.     public static final String METHOD_GET = "GET";    
  26.     public static final String CONTENT_TYPE = "Content-Type";    
  27.    
  28.     /** 
  29.      * 以POST方式向指定地址发送数据包请求,并取得返回的数据包 
  30.      *  
  31.      * @param urlString 
  32.      * @param requestData 
  33.      * @return 返回数据包 
  34.      * @throws Exception 
  35.      */   
  36.     public static byte[] requestPost(String urlString, byte[] requestData)    
  37.             throws Exception {    
  38.         Properties requestProperties = new Properties();    
  39.         requestProperties.setProperty(CONTENT_TYPE,    
  40.                 "application/octet-stream; charset=utf-8");    
  41.    
  42.         return requestPost(urlString, requestData, requestProperties);    
  43.     }    
  44.    
  45.     /** 
  46.      * 以POST方式向指定地址发送数据包请求,并取得返回的数据包 
  47.      *  
  48.      * @param urlString 
  49.      * @param requestData 
  50.      * @param requestProperties 
  51.      * @return 返回数据包 
  52.      * @throws Exception 
  53.      */   
  54.     public static byte[] requestPost(String urlString, byte[] requestData,    
  55.             Properties requestProperties) throws Exception {    
  56.         byte[] responseData = null;    
  57.    
  58.         HttpURLConnection con = null;    
  59.    
  60.         try {    
  61.             URL url = new URL(urlString);    
  62.             con = (HttpURLConnection) url.openConnection();    
  63.    
  64.             if ((requestProperties != null) && (requestProperties.size() > 0)) {    
  65.                 for (Map.Entry<Object, Object> entry : requestProperties    
  66.                         .entrySet()) {    
  67.                     String key = String.valueOf(entry.getKey());    
  68.                     String value = String.valueOf(entry.getValue());    
  69.                     con.setRequestProperty(key, value);    
  70.                 }    
  71.             }    
  72.    
  73.             con.setRequestMethod(METHOD_POST); // 置为POST方法    
  74.    
  75.             con.setDoInput(true); // 开启输入流    
  76.             con.setDoOutput(true); // 开启输出流    
  77.    
  78.             // 如果请求数据不为空,输出该数据。    
  79.             if (requestData != null) {    
  80.                 DataOutputStream dos = new DataOutputStream(con    
  81.                         .getOutputStream());    
  82.                 dos.write(requestData);    
  83.                 dos.flush();    
  84.                 dos.close();    
  85.             }    
  86.    
  87.             int length = con.getContentLength();    
  88.             // 如果回复消息长度不为-1,读取该消息。    
  89.             if (length != -1) {    
  90.                 DataInputStream dis = new DataInputStream(con.getInputStream());    
  91.                 responseData = new byte[length];    
  92.                 dis.readFully(responseData);    
  93.                 dis.close();    
  94.             }    
  95.         } catch (Exception e) {    
  96.             throw e;    
  97.         } finally {    
  98.             if (con != null) {    
  99.                 con.disconnect();    
  100.                 con = null;    
  101.             }    
  102.         }    
  103.    
  104.         return responseData;    
  105.     }    
  106.    
  107.     /** 
  108.      * 以POST方式向指定地址提交表单<br> 
  109.      * arg0=urlencode(value0)&arg1=urlencode(value1) 
  110.      *  
  111.      * @param urlString 
  112.      * @param formProperties 
  113.      * @return 返回数据包 
  114.      * @throws Exception 
  115.      */   
  116.     public static byte[] requestPostForm(String urlString,    
  117.             Properties formProperties) throws Exception {    
  118.         return requestPostForm(urlString, formProperties, null);    
  119.     }    
  120.    
  121.     /** 
  122.      * 以POST方式向指定地址提交表单<br> 
  123.      * arg0=urlencode(value0)&arg1=urlencode(value1) 
  124.      *  
  125.      * @param urlString 
  126.      * @param formProperties 
  127.      * @param requestProperties 
  128.      * @return 返回数据包 
  129.      * @throws Exception 
  130.      */   
  131.     public static byte[] requestPostForm(String urlString,    
  132.             Properties formProperties, Properties requestProperties)    
  133.             throws Exception {    
  134.         requestProperties.setProperty(HttpUtils.CONTENT_TYPE,    
  135.                 "application/x-www-form-urlencoded");    
  136.    
  137.         StringBuilder sb = new StringBuilder();    
  138.    
  139.         if ((formProperties != null) && (formProperties.size() > 0)) {    
  140.             for (Map.Entry<Object, Object> entry : formProperties.entrySet()) {    
  141.                 String key = String.valueOf(entry.getKey());    
  142.                 String value = String.valueOf(entry.getValue());    
  143.                 sb.append(key);    
  144.                 sb.append("=");    
  145.                 sb.append(encode(value));    
  146.                 sb.append("&");    
  147.             }    
  148.         }    
  149.    
  150.         String str = sb.toString();    
  151.         str = str.substring(0, (str.length() - 1)); // 截掉末尾字符&    
  152.    
  153.         return requestPost(urlString, str.getBytes(CHARACTER_ENCODING),    
  154.                 requestProperties);    
  155.    
  156.     }    
  157.    
  158.     /** 
  159.      * url解码 
  160.      *  
  161.      * @param str 
  162.      * @return 解码后的字符串,当异常时返回原始字符串。 
  163.      */   
  164.     public static String decode(String url) {    
  165.         try {    
  166.             return URLDecoder.decode(url, CHARACTER_ENCODING);    
  167.         } catch (UnsupportedEncodingException ex) {    
  168.             return url;    
  169.         }    
  170.     }    
  171.    
  172.     /** 
  173.      * url编码 
  174.      *  
  175.      * @param str 
  176.      * @return 编码后的字符串,当异常时返回原始字符串。 
  177.      */   
  178.     public static String encode(String url) {    
  179.         try {    
  180.             return URLEncoder.encode(url, CHARACTER_ENCODING);    
  181.         } catch (UnsupportedEncodingException ex) {    
  182.             return url;    
  183.         }    
  184.     }    
  185. }   
  186.  
  187. /**
  188. * 2008-12-26
  189. */  
  190. package org.zlex.commons.net;  
  191.  
  192. import java.io.DataInputStream;  
  193. import java.io.DataOutputStream;  
  194. import java.io.UnsupportedEncodingException;  
  195. import java.net.HttpURLConnection;  
  196. import java.net.URL;  
  197. import java.net.URLDecoder;  
  198. import java.net.URLEncoder;  
  199. import java.util.Map;  
  200. import java.util.Properties;  
  201.  
  202. /**
  203. * 网络工具
  204. *
  205. * @author 梁栋
  206. * @version 1.0
  207. * @since 1.0
  208. */  
  209. public abstract class NetUtils {  
  210. public static final String CHARACTER_ENCODING = "UTF-8";  
  211. public static final String PATH_SIGN = "/";  
  212. public static final String METHOD_POST = "POST";  
  213. public static final String METHOD_GET = "GET";  
  214. public static final String CONTENT_TYPE = "Content-Type";  
  215.  
  216. /**
  217. * 以POST方式向指定地址发送数据包请求,并取得返回的数据包
  218. *
  219. * @param urlString
  220. * @param requestData
  221. * @return 返回数据包
  222. * @throws Exception
  223. */  
  224. public static byte[] requestPost(String urlString, byte[] requestData)  
  225. throws Exception {  
  226. Properties requestProperties = new Properties();  
  227. requestProperties.setProperty(CONTENT_TYPE,  
  228. "application/octet-stream; charset=utf-8");  
  229.  
  230. return requestPost(urlString, requestData, requestProperties);  
  231. }  
  232.  
  233. /**
  234. * 以POST方式向指定地址发送数据包请求,并取得返回的数据包
  235. *
  236. * @param urlString
  237. * @param requestData
  238. * @param requestProperties
  239. * @return 返回数据包
  240. * @throws Exception
  241. */  
  242. public static byte[] requestPost(String urlString, byte[] requestData,  
  243. Properties requestProperties) throws Exception {  
  244. byte[] responseData = null;  
  245.  
  246. HttpURLConnection con = null;  
  247.  
  248. try {  
  249. URL url = new URL(urlString);  
  250. con = (HttpURLConnection) url.openConnection();  
  251.  
  252. if ((requestProperties != null) && (requestProperties.size() > 0)) {  
  253. for (Map.Entry<Object, Object> entry : requestProperties  
  254. .entrySet()) {  
  255. String key = String.valueOf(entry.getKey());  
  256. String value = String.valueOf(entry.getValue());  
  257. con.setRequestProperty(key, value);  
  258. }  
  259. }  
  260.  
  261. con.setRequestMethod(METHOD_POST); // 置为POST方法  
  262.  
  263. con.setDoInput(true); // 开启输入流  
  264. con.setDoOutput(true); // 开启输出流  
  265.  
  266. // 如果请求数据不为空,输出该数据。  
  267. if (requestData != null) {  
  268. DataOutputStream dos = new DataOutputStream(con  
  269. .getOutputStream());  
  270. dos.write(requestData);  
  271. dos.flush();  
  272. dos.close();  
  273. }  
  274.  
  275. int length = con.getContentLength();  
  276. // 如果回复消息长度不为-1,读取该消息。  
  277. if (length != -1) {  
  278. DataInputStream dis = new DataInputStream(con.getInputStream());  
  279. responseData = new byte[length];  
  280. dis.readFully(responseData);  
  281. dis.close();  
  282. }  
  283. } catch (Exception e) {  
  284. throw e;  
  285. } finally {  
  286. if (con != null) {  
  287. con.disconnect();  
  288. con = null;  
  289. }  
  290. }  
  291.  
  292. return responseData;  
  293. }  
  294.  
  295. /**
  296. * 以POST方式向指定地址提交表单<br>
  297. * arg0=urlencode(value0)&arg1=urlencode(value1)
  298. *
  299. * @param urlString
  300. * @param formProperties
  301. * @return 返回数据包
  302. * @throws Exception
  303. */  
  304. public static byte[] requestPostForm(String urlString,  
  305. Properties formProperties) throws Exception {  
  306. return requestPostForm(urlString, formProperties, null);  
  307. }  
  308.  
  309. /**
  310. * 以POST方式向指定地址提交表单<br>
  311. * arg0=urlencode(value0)&arg1=urlencode(value1)
  312. *
  313. * @param urlString
  314. * @param formProperties
  315. * @param requestProperties
  316. * @return 返回数据包
  317. * @throws Exception
  318. */  
  319. public static byte[] requestPostForm(String urlString,  
  320. Properties formProperties, Properties requestProperties)  
  321. throws Exception {  
  322. requestProperties.setProperty(HttpUtils.CONTENT_TYPE,  
  323. "application/x-www-form-urlencoded");  
  324.  
  325. StringBuilder sb = new StringBuilder();  
  326.  
  327. if ((formProperties != null) && (formProperties.size() > 0)) {  
  328. for (Map.Entry<Object, Object> entry : formProperties.entrySet()) {  
  329. String key = String.valueOf(entry.getKey());  
  330. String value = String.valueOf(entry.getValue());  
  331. sb.append(key);  
  332. sb.append("=");  
  333. sb.append(encode(value));  
  334. sb.append("&");  
  335. }  
  336. }  
  337.  
  338. String str = sb.toString();  
  339. str = str.substring(0, (str.length() - 1)); // 截掉末尾字符&  
  340.  
  341. return requestPost(urlString, str.getBytes(CHARACTER_ENCODING),  
  342. requestProperties);  
  343.  
  344. }  
  345.  
  346. /**
  347. * url解码
  348. *
  349. * @param str
  350. * @return 解码后的字符串,当异常时返回原始字符串。
  351. */  
  352. public static String decode(String url) {  
  353. try {  
  354. return URLDecoder.decode(url, CHARACTER_ENCODING);  
  355. } catch (UnsupportedEncodingException ex) {  
  356. return url;  
  357. }  
  358. }  
  359.  
  360. /**
  361. * url编码
  362. *
  363. * @param str
  364. * @return 编码后的字符串,当异常时返回原始字符串。
  365. */  
  366. public static String encode(String url) {  
  367. try {  
  368. return URLEncoder.encode(url, CHARACTER_ENCODING);  
  369. } catch (UnsupportedEncodingException ex) {  
  370. return url;  
  371. }  
  372. }  
  373. }  
  374.  
  375.  
  376. 注意上述requestPostForm()方法,是用来提交表单的。  
  377. 测试用例  
  378. Java代码  
  379. /** 
  380. * 2009-8-21 
  381. */   
  382. package org.zlex.commons.net;    
  383.    
  384. import static org.junit.Assert.*;    
  385.    
  386. import java.util.Properties;    
  387.    
  388. import org.junit.Test;    
  389.    
  390. /** 
  391. * 网络工具测试 
  392. *  
  393. * @author 梁栋 
  394. * @version 1.0 
  395. * @since 1.0 
  396. */   
  397. public class NetUtilsTest {    
  398.    
  399.     /** 
  400.      * Test method for 
  401.      * {@link org.zlex.commons.net.NetUtils#requestPost(java.lang.String, byte[])} 
  402.      * . 
  403.      */   
  404.     @Test   
  405.     public final void testRequestPostStringByteArray() throws Exception {    
  406.         Properties requestProperties = new Properties();    
  407.    
  408.         // 模拟浏览器信息    
  409.         requestProperties    
  410.                 .put(    
  411.                         "User-Agent",    
  412.                         "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; TencentTraveler ; .NET CLR 1.1.4322)");    
  413.    
  414.         byte[] b = NetUtils.requestPost("http://localhost:8080/zlex/post.do",    
  415.                 "XML".getBytes());    
  416.         System.err.println(new String(b, "utf-8"));    
  417.     }    
  418.    
  419.     /** 
  420.      * Test method for 
  421.      * {@link org.zlex.commons.net.NetUtils#requestPostForm(java.lang.String, java.util.Properties)} 
  422.      * . 
  423.      */   
  424.     @Test   
  425.     public final void testRequestPostForm() throws Exception {    
  426.         Properties formProperties = new Properties();    
  427.    
  428.         formProperties.put("j_username", "Admin");    
  429.         formProperties.put("j_password", "manage");    
  430.    
  431.         byte[] b = NetUtils.requestPostForm(    
  432.                 "http://localhost:8080/zlex/j_spring_security_check",    
  433.                 formProperties);    
  434.         System.err.println(new String(b, "utf-8"));    
  435.     }    
  436. }  

最近做一接口,要通过JAVA类请求SERVLET ,DOPOST方法.
不知道怎么把我的参数传过去.在网上找了几个例子.
都不行.
方法一:

  1. package com.3sfg.setvlet; 
  2.  
  3. import java.io.BufferedReader; 
  4. import java.io.IOException; 
  5. import java.io.InputStreamReader; 
  6. import java.util.HashMap; 
  7. import java.util.Map; 
  8.  
  9. import org.apache.commons.httpclient.HttpClient; 
  10. import org.apache.commons.httpclient.HttpMethod; 
  11. import org.apache.commons.httpclient.HttpStatus; 
  12. import org.apache.commons.httpclient.URIException; 
  13. import org.apache.commons.httpclient.methods.GetMethod; 
  14. import org.apache.commons.httpclient.methods.PostMethod; 
  15. import org.apache.commons.httpclient.params.HttpMethodParams; 
  16. import org.apache.commons.httpclient.util.URIUtil; 
  17. import org.apache.commons.lang.StringUtils; 
  18. import org.apache.commons.logging.Log; 
  19. import org.apache.commons.logging.LogFactory; 
  20.  
  21. /**
  22. * HTTP工具箱
  23. *
  24. * @author leizhimin 2009-6-19 16:36:18
  25. */  
  26. public final class HttpTookit {  
  27.         private static Log log = LogFactory.getLog(HttpTookit.class);  
  28.  
  29.         /**
  30.          * 执行一个HTTP GET请求,返回请求响应的HTML
  31.          *
  32.          * @param url                 请求的URL地址
  33.          * @param queryString 请求的查询参数,可以为null
  34.          * @param charset         字符集
  35.          * @param pretty            是否美化
  36.          * @return 返回请求响应的HTML
  37.          */  
  38.         public static String doGet(String url, String queryString, String charset, boolean pretty) {  
  39.                 StringBuffer response = new StringBuffer();  
  40.                 HttpClient client = new HttpClient();  
  41.                 HttpMethod method = new GetMethod(url);  
  42.                 try {  
  43.                         if (StringUtils.isNotBlank(queryString))  
  44.                                 //对get请求参数做了http请求默认编码,好像没有任何问题,汉字编码后,就成为%式样的字符串  
  45.                                 method.setQueryString(URIUtil.encodeQuery(queryString));  
  46.                         client.executeMethod(method);  
  47.                         if (method.getStatusCode() == HttpStatus.SC_OK) {  
  48.                                 BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));  
  49.                                 String line;  
  50.                                 while ((line = reader.readLine()) != null) {  
  51.                                         if (pretty)  
  52.                                                 response.append(line).append(System.getProperty("line.separator"));  
  53.                                         else  
  54.                                                 response.append(line);  
  55.                                 }  
  56.                                 reader.close();  
  57.                         }  
  58.                 } catch (URIException e) {  
  59.                         log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);  
  60.                 } catch (IOException e) {  
  61.                         log.error("执行HTTP Get请求" + url + "时,发生异常!", e);  
  62.                 } finally {  
  63.                         method.releaseConnection();  
  64.                 }  
  65.                 return response.toString();  
  66.         }  
  67.  
  68.         /**
  69.          * 执行一个HTTP POST请求,返回请求响应的HTML
  70.          *
  71.          * @param url         请求的URL地址
  72.          * @param params    请求的查询参数,可以为null
  73.          * @param charset 字符集
  74.          * @param pretty    是否美化
  75.          * @return 返回请求响应的HTML
  76.          */  
  77.         public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) {  
  78.                 StringBuffer response = new StringBuffer();  
  79.                 HttpClient client = new HttpClient();  
  80.                 HttpMethod method = new PostMethod(url);  
  81.                 //设置Http Post数据  
  82.                 if (params != null) {  
  83.                         HttpMethodParams p = new HttpMethodParams();  
  84.                         for (Map.Entry<String, String> entry : params.entrySet()) {  
  85.                                 p.setParameter(entry.getKey(), entry.getValue());  
  86.                         } 
  87.                         p.setParameter("abc", "efg"); 
  88.                         method.setParams(p);  
  89.                 }  
  90.                 try {  
  91.                         client.executeMethod(method);  
  92.                         if (method.getStatusCode() == HttpStatus.SC_OK) {  
  93.                                 BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));  
  94.                                 String line;  
  95.                                 while ((line = reader.readLine()) != null) {  
  96.                                         if (pretty)  
  97.                                                 response.append(line).append(System.getProperty("line.separator"));  
  98.                                         else  
  99.                                                 response.append(line);  
  100.                                 }  
  101.                                 reader.close();  
  102.                         }  
  103.                 } catch (IOException e) {  
  104.                         log.error("执行HTTP Post请求" + url + "时,发生异常!", e);  
  105.                 } finally {  
  106.                         method.releaseConnection();  
  107.                 }  
  108.                 return response.toString();  
  109.         }  
  110.  
  111.         public static void main(String[] args) { 
  112.             Map<String, String> map = new HashMap<String, String>(); 
  113.             map.put("parax", "123456"); 
  114.                 String y = doGet("http://127.0.0.1:8080/AIRP/servletTest", "xx=00", "GBK", true);  
  115.                 String z = doPost("http://127.0.0.1:8080/AIRP/servletTest?", map, "GBK", false);  
  116.                 System.out.println(y);  
  117.                 System.out.println(z);  
  118.         }  

POST 方法 ,我在servletJ里,取不知任何参数,请求帮助.
感谢.
方法二:

  1. private static String testPost(String MSG_ID,String MOBILE_NO,String CONTENT, 
  2.         String SERVICE_ID,String PASS,String SP_CODE,String LINK_ID, 
  3.          String FEE_TYPE,String FEE_CODE) throws IOException {       
  4.        
  5.       URL url = new URL("http://127.0.0.1:8080/AIRP/servletTest");       
  6.       URLConnection connection = url.openConnection();       
  7.  
  8.       connection.setDoOutput(true);         
  9.       OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");       
  10.       out.write("MSG_ID="+MSG_ID+"&MOBILE_NO="+MOBILE_NO+"&ACTION_ID=3" 
  11.             +"&SERVICE_ID=99&PASS=asdfasd" 
  12.             +"&SP_CODE=10625777&LINK_ID="); //向页面传递数据。post的关键所在!       
  13.       // remember to clean up       
  14.       out.flush();       
  15.       out.close();       
  16.       
  17.       String sCurrentLine;       
  18.       String sTotalString;       
  19.       sCurrentLine = ""
  20.       sTotalString = ""
  21.       InputStream l_urlStream; 
  22.       l_urlStream = connection.getInputStream();       
  23.       // 传说中的三层包装阿!       
  24.       BufferedReader l_reader = new BufferedReader(new InputStreamReader(       
  25.               l_urlStream));       
  26.       while ((sCurrentLine = l_reader.readLine()) != null) {       
  27.           sTotalString += sCurrentLine + "/r/n";       
  28.     
  29.       }       
  30.       System.out.println(sTotalString);  
  31.       return sTotalString; 
  32.   } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值