1,可以使用最基本的流對象 URL對象直接将請求封裝 然後發送
/**
*
* HTTP + POST 發送将對象發送出去
*/
// String url="http://127.0.0.1:8088/ToolStore/up_registerPhonePay.action?username='liuyang'&age=18";
// /**
// * 參數資訊
// * MBL_NO 1 String 11 手機号
// * TTXN_TM 1 String 14 交易請求時間 YYYYMMDDhhmmss
// * TTXN_CNL 1 String 5 交易請求管道
// * SIG_VAL 1 String 1024(變長) 數字簽名(大寫) 見附錄1
// */
//
// PrintWriter out = null;
// BufferedReader in = null;
// String result = "";
// 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 += "\n" + line;
// }
// }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;
2,可以使用apache提供common HttpClient jar包中得現成的方法,比較簡單明了。
/**
*
* apache common client發送post / get 請求
*/
HttpClient httpclient=new HttpClient();
//post請求
PostMethod postmethod=new PostMethod("http://127.0.0.1:8088/ToolStore/up_registerPhonePay.action");
NameValuePair[] postData=new NameValuePair[2];
postData[0]=new NameValuePair("username","liuyang");
postData[1]=new NameValuePair("age","21");
postmethod.addParameters(postData);
//get請求
// GetMethod getmethod=new GetMethod("http://www.baidu.com");
// //傳回結果int
int sendStatus=0;
try {
sendStatus=httpclient.executeMethod(postmethod);
System.out.println("response=" + postmethod.getResponseBodyAsString());
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//釋放
postmethod.releaseConnection();
}