標籤:輸入 close cancel task line number 欄位 內容 iter
在網上找了好久都沒有找到post、get請求的工具類,如今整理了一下分享出來。http工具類例如以下:
package com.qlwb.business.util;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.lang.reflect.Field;import java.net.URL;import java.net.URLConnection;import java.util.List;import java.util.Map;import java.util.Timer;import java.util.TimerTask;import net.sf.json.JSONObject;import org.apache.log4j.Logger;/** * * * @類編號: * @類名稱:HttpRequest * @內容摘要: http post get請求 * @author:鹿偉偉 * @建立日期:2016年4月13日 下午4:03:50 * @改動人: * @改動日期: * @改動描寫敘述:簡單描寫敘述改動的內容 * @version 1.0.0 * */public class HttpRequest { /** * 向指定URL發送GET方法的請求 * * @param url * 發送請求的URL * @param param * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return URL 所代表遠端資源的響應結果 */ public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?
" + param; URL realUrl = new URL(urlNameString); // 開啟和URL之間的串連 URLConnection connection = realUrl.openConnection(); // 設定通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立實際的串連 connection.connect(); // 擷取全部回應標頭欄位 Map<String, List<String>> map = connection.getHeaderFields(); // 遍曆全部的回應標頭欄位 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定義 BufferedReader輸入資料流來讀取URL的響應 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("發送GET請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸入資料流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 發送POST方法的請求 * * @param url * 發送請求的 URL * @param param * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 * @return 所代表遠端資源的響應結果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; Logger.getLogger(HttpRequest.class).info("流量儲值開始:"+url+"&"+param); try { URL realUrl = new URL(url); // 開啟和URL之間的串連 URLConnection conn = realUrl.openConnection(); // 設定通用的請求屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 發送POST請求必須設定例如以下兩行 conn.setDoOutput(true); conn.setDoInput(true); // 擷取URLConnection對象相應的輸出資料流 out = new PrintWriter(conn.getOutputStream()); // 發送請求參數 out.print(param); // flush輸出資料流的緩衝 out.flush(); // 定義BufferedReader輸入資料流來讀取URL的響應 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } Logger.getLogger(HttpRequest.class).info("流量儲值結束:"+result); } catch (Exception e) { System.out.println("發送 POST 請求出現異常。" + e); e.printStackTrace(); } // 使用finally塊來關閉輸出資料流、輸入資料流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } public static String formatParam(Object o) { StringBuffer sbf= new StringBuffer(); Class cls = o.getClass(); Field[] fields = cls.getDeclaredFields(); try { for (Field f : fields) { f.setAccessible(true); if (!"serialVersionUID".equals(f.getName())) { sbf.append(f.getName() + "=" + (f.get(o)==null?"":f.get(o) )+ "&"); }// if (f.get(o) != null && f.get(o) != "") {// } } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sbf.toString().substring(0, sbf.toString().length()-1); } public static void main(String[] args) {// ThirdRechargeReqParams p=new ThirdRechargeReqParams();// p.setMobile("18706402245");// p.setOrderMeal("10");// p.setMsgId("123456");// p.setRange("0");// System.out.println(p.toString());// System.out.println(CreditMallHandle.ThirdFlowRecharge(p));// Timer timer = new Timer(); // timer.schedule(new RequestTask(), 1000,6*1000);// timer.cancel(); JSONObject bodyObj = JSONObject.fromObject(HttpRequest.sendPost("http://api.wxflow.com:9092/Public/Api/?service=User.buyFlowOrderInfo", "userName=qlyd&userPwd=27e3b7118777a1114fb0c9cc0052d31a614c55da&mobile=18706402245&orderMeal=20&orderTime=1&msgId=23213&extend=&range=0")); System.out.println(bodyObj.getJSONObject("data").getString("code")); }}
Http請求get、post工具類