1. 程式人生 > >HttpSenderUtil向指定 URL 傳送POST方法的請求

HttpSenderUtil向指定 URL 傳送POST方法的請求

package com.founder.ec.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.URIException; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.util.URIUtil; import org.apache.commons.lang.StringUtils; import org.apache.commons.httpclient.HttpException; public class HttpSenderUtil { /** * 向指定 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 = ""; 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; } } 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 httpSend(String url, Map<String, Object> propsMap) throws Exception{ HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url);// POST請求 String returnString =""; // 引數設定 Set<String> keySet = propsMap.keySet(); NameValuePair[] postData = new NameValuePair[keySet.size()]; int index = 0; for (String key : keySet) { postData[index++] = new NameValuePair(key, propsMap.get(key).toString()); } postMethod.addParameters(postData); try { httpClient.executeMethod(postMethod);// 傳送請求 java.io.InputStream input = postMethod.getResponseBodyAsStream(); returnString = convertStreamToString(input).toString(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { postMethod.releaseConnection();// 關閉連線 } return returnString; } public static String convertStreamToString(java.io.InputStream input) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } input.close(); return sb.toString(); } public static void main(String[] strs){ long time=new Date().getTime(); String check=MD5.getMD5(time+"www.j1.com"); String mobile="13053702096"; String msg="尊敬的使用者 , 您在健一網的安全驗證碼為897489,健一網祝您身體健康"; String param="t="+time+"&mobile="+mobile+"&msg="+msg+"&check="+check; String res=HttpSenderUtil.sendPost("http://localhost:8080/ec-dec/page/sms/sendSms/code",param); System.out.println(res); } /** * 執行get方法 * @param url * @param queryString * @return */ public static String doGet(String url, String queryString) { String response = null; HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); try { if (StringUtils.isNotBlank(queryString)) method.setQueryString(URIUtil.encodeQuery(queryString)); client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { response = method.getResponseBodyAsString(); } } catch (URIException e) { //logger.error("執行HTTP Get請求時,編碼查詢字串“" + queryString + "”發生異常!", e); } catch (IOException e) { //logger.error("執行HTTP Get請求" + url + "時,發生異常!", e); } finally { method.releaseConnection(); } return response; } }