http://bijian1013.iteye.com/blog/2310211
在發送HTTP請求的時候會使用到POST和GET兩種方式,如果是傳送普通的表單數據,我們直接將參數到一個Key-value形式的Map中即可,隨着JSON的應用越來越廣,我們在很多場合需要傳送JSON格式的參數。
下面我使用HttpClient類庫提供的功能來實現這個,以便以后參考。
一.完善SpringMVC工程
完善SpringMVC工程(修改之前的Spring工程地址:http://bijian1013.iteye.com/blog/2307353),使其不僅支持GET、POST兩種方式的請求,且支持普通表單數據請求和JSON格式的兩種請求數據,完整工程代碼見附件《SpringMVC.zip》,日志相關的依賴jar包可直接從HttpClient.zip中獲取到。
- @Controller
- public class HelloController {
- private static Logger logger = LoggerFactory.getLogger(HelloController.class);
- @Autowired
- private HelloService helloService;
- @RequestMapping("/greeting")
- public ModelAndView greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
- Map<String, Object> map = new HashMap<String, Object>();
- try {
- //由於瀏覽器會把中文直接換成ISO-8859-1編碼格式,如果用戶在地址打入中文,需要進行如下轉換處理
- String tempName = new String(name.getBytes("ISO-8859-1"), "utf-8");
- logger.trace("tempName:" + tempName);
- logger.info(tempName);
- String userName = helloService.processService(tempName);
- map.put("userName", userName);
- logger.trace("運行結果:" + map);
- } catch (UnsupportedEncodingException e) {
- logger.error("HelloController greeting方法發生UnsupportedEncodingException異常:" + e);
- } catch (Exception e) {
- logger.error("HelloController greeting方法發生Exception異常:" + e);
- }
- return new ModelAndView("/hello", map);
- }
- @RequestMapping(value="/processing", method = RequestMethod.POST)
- public ModelAndView processing(HttpServletRequest request, HttpServletResponse response) {
- Enumeration en = request.getParameterNames();
- while (en.hasMoreElements()) {
- String paramName = (String) en.nextElement();
- String paramValue = request.getParameter(paramName);
- }
- String name = request.getParameter("name");
- String age = request.getParameter("age");
- UserDTO userDTO = new UserDTO();
- userDTO.setName(name);
- userDTO.setAge(Integer.valueOf(age));
- logger.info("process param is :{}" + userDTO);
- Map<String, Object> map = new HashMap<String, Object>();
- try {
- userDTO = helloService.processService(userDTO);
- //返回請求結果
- map.put("name", userDTO.getName());
- map.put("age", userDTO.getAge());
- } catch (Exception e) {
- logger.info("請求處理異常:" + e);
- }
- return new ModelAndView("/user", map);
- }
- /**
- * @responseBody表示該方法的返回結果直接寫入HTTP response body中
- * 一般在異步獲取數據時使用,在使用@RequestMapping后,返回值通常解析為跳轉路徑
- * 加上@responseBody后返回結果不會被解析為跳轉路徑,而是直接寫入HTTP response body中。
- * 比如異步獲取json數據,加上@responsebody后,會直接返回json數據。
- */
- @ResponseBody
- @RequestMapping(value="/greet",method = RequestMethod.GET)
- public Map<String, Object> greet(HttpServletRequest request, HttpServletResponse response,
- @RequestParam(value = "name", defaultValue = "World") String name) {
- Map<String, Object> map = null;
- try {
- //由於瀏覽器會把中文直接換成ISO-8859-1編碼格式,如果用戶在地址打入中文,需要進行如下轉換處理
- String tempName = new String(name.getBytes("ISO-8859-1"), "utf-8");
- logger.trace("tempName:" + tempName);
- logger.info(tempName);
- String userName = helloService.processService(tempName);
- map = new HashMap<String, Object>();
- map.put("userName", userName);
- logger.trace("運行結果:" + map);
- } catch (UnsupportedEncodingException e) {
- logger.error("HelloController greet方法發生UnsupportedEncodingException異常:" + e);
- } catch (Exception e) {
- logger.error("HelloController greet方法發生Exception異常:" + e);
- }
- return map;
- }
- @ResponseBody
- @RequestMapping(value="/process",method = RequestMethod.POST)
- public String process(HttpServletRequest request, @RequestBody String requestBody) {
- logger.info("process param is :{}" + requestBody);
- JSONObject result = new JSONObject();
- try {
- JSONObject jsonObject = JSONObject.fromObject(requestBody);
- UserDTO userDTO = (UserDTO) JSONObject.toBean(jsonObject, UserDTO.class);
- userDTO = helloService.processService(userDTO);
- //返回請求結果
- result.put("status", "SUCCESS");
- result.put("userDTO", userDTO);
- } catch (Exception e) {
- logger.info("請求處理異常! params is:{}", requestBody);
- result.put("status", "FAIL");
- }
- return result.toString();
- }
- }
二.HttpClient請求普通的表單數據,返回HTML頁面
- package com.bijian.study;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Map;
- import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
- import org.apache.commons.httpclient.Header;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.HttpException;
- import org.apache.commons.httpclient.HttpMethod;
- import org.apache.commons.httpclient.HttpStatus;
- import org.apache.commons.httpclient.NameValuePair;
- import org.apache.commons.httpclient.methods.GetMethod;
- import org.apache.commons.httpclient.methods.PostMethod;
- import org.apache.commons.httpclient.params.HttpMethodParams;
- import org.apache.http.client.methods.HttpPost;
- /**
- * Http請求工具類
- * 請求的是普通的表單數據,返回HTML頁面
- *
- * 需要導入commons-codec-1.3.jar
- */
- public class HttpClientUtil {
- /**
- * httpClient的get請求方式
- *
- * @param url
- * @param charset
- * @return
- * @throws Exception
- */
- public static String doGet(String url, String charset) throws Exception {
- HttpClient client = new HttpClient();
- GetMethod method = new GetMethod(url);
- if (null == url || !url.startsWith("http")) {
- throw new Exception("請求地址格式不對");
- }
- // 設置請求的編碼方式
- if (null != charset) {
- method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + charset);
- } else {
- method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + "utf-8");
- }
- int statusCode = client.executeMethod(method);
- if (statusCode != HttpStatus.SC_OK) {// 打印服務器返回的狀態
- System.out.println("Method failed: " + method.getStatusLine());
- }
- // 返回響應消息
- byte[] responseBody = method.getResponseBodyAsString().getBytes(method.getResponseCharSet());
- // 在返回響應消息使用編碼(utf-8或gb2312)
- String response = new String(responseBody, "utf-8");
- System.out.println("------------------response:" + response);
- // 釋放連接
- method.releaseConnection();
- return response;
- }
- /**
- * httpClient的get請求方式2
- *
- * @param url
- * @param charset
- * @return
- * @throws Exception
- */
- public static String doGet2(String url, String charset) throws Exception {
- /*
- * 使用 GetMethod 來訪問一個 URL 對應的網頁,實現步驟: 1:生成一個 HttpClinet 對象並設置相應的參數。
- * 2:生成一個 GetMethod 對象並設置響應的參數。 3:用 HttpClinet 生成的對象來執行 GetMethod 生成的Get
- * 方法。 4:處理響應狀態碼。 5:若響應正常,處理 HTTP 響應內容。 6:釋放連接。
- */
- /* 1 生成 HttpClinet 對象並設置參數 */
- HttpClient httpClient = new HttpClient();
- // 設置 Http 連接超時為5秒
- httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
- /* 2 生成 GetMethod 對象並設置參數 */
- GetMethod getMethod = new GetMethod(url);
- // 設置 get 請求超時為 5 秒
- getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
- // 設置請求重試處理,用的是默認的重試處理:請求三次
- getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
- String response = "";
- /* 3 執行 HTTP GET 請求 */
- try {
- int statusCode = httpClient.executeMethod(getMethod);
- /* 4 判斷訪問的狀態碼 */
- if (statusCode != HttpStatus.SC_OK) {
- System.err.println("Method failed: " + getMethod.getStatusLine());
- }
- /* 5 處理 HTTP 響應內容 */
- // HTTP響應頭部信息,這里簡單打印
- Header[] headers = getMethod.getResponseHeaders();
- for (Header h : headers)
- System.out.println(h.getName() + "------------ " + h.getValue());
- // 讀取 HTTP 響應內容,這里簡單打印網頁內容
- byte[] responseBody = getMethod.getResponseBody();// 讀取為字節數組
- response = new String(responseBody, charset);
- System.out.println("----------response:" + response);
- // 讀取為 InputStream,在網頁內容數據量大時候推薦使用
- // InputStream response = getMethod.getResponseBodyAsStream();
- } catch (HttpException e) {
- // 發生致命的異常,可能是協議不對或者返回的內容有問題
- System.out.println("Please check your provided http address!");
- e.printStackTrace();
- } catch (IOException e) {
- // 發生網絡異常
- e.printStackTrace();
- } finally {
- /* 6 .釋放連接 */
- getMethod.releaseConnection();
- }
- return response;
- }
- /**
- * 執行一個HTTP POST請求,返回請求響應的HTML
- *
- * @param url 請求的URL地址
- * @param params 請求的查詢參數,可以為null
- * @param charset 字符集
- * @param pretty 是否美化
- * @return 返回請求響應的HTML
- */
- public static String doPost(String url, Map<String, Object> _params, String charset, boolean pretty) {
- StringBuffer response = new StringBuffer();
- HttpClient client = new HttpClient();
- PostMethod method = new PostMethod(url);
- // 設置Http Post數據
- if (_params != null) {
- for (Map.Entry<String, Object> entry : _params.entrySet()) {
- method.setParameter(entry.getKey(), String.valueOf(entry.getValue()));
- }
- }
- // 設置Http Post數據 方法二
- // if(_params != null) {
- // NameValuePair[] pairs = new NameValuePair[_params.size()];//純參數了,鍵值對
- // int i = 0;
- // for (Map.Entry<String, Object> entry : _params.entrySet()) {
- // pairs[i] = new NameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
- // i++;
- // }
- // method.addParameters(pairs);
- // }
- try {
- client.executeMethod(method);
- if (method.getStatusCode() == HttpStatus.SC_OK) {
- // 讀取為 InputStream,在網頁內容數據量大時候推薦使用
- BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(),
- charset));
- String line;
- while ((line = reader.readLine()) != null) {
- if (pretty)
- response.append(line).append(System.getProperty("line.separator"));
- else
- response.append(line);
- }
- reader.close();
- }
- } catch (IOException e) {
- System.out.println("執行HTTP Post請求" + url + "時,發生異常!");
- e.printStackTrace();
- } finally {
- method.releaseConnection();
- }
- System.out.println("--------------------" + response.toString());
- return response.toString();
- }
- }
測試類HttpClientTest.java
- package com.bijian.study;
- import java.util.HashMap;
- import java.util.Map;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- public class HttpClientTest {
- private static Logger logger = LoggerFactory.getLogger(HttpRequestTest.class);
- public static void main(String[] args) {
- getRequestTest();
- getRequestTest2();
- postRequestTest();
- }
- private static void getRequestTest() {
- String url = "http://localhost:8080/SpringMVC/greeting?name=lisi";
- try {
- String str = HttpClientUtil.doGet(url, "UTF-8");
- if (str != null) {
- logger.info("http Get request result:" + str);
- } else {
- logger.info("http Get request process fail");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private static void getRequestTest2() {
- String url = "http://localhost:8080/SpringMVC/greeting?name=lisi";
- try {
- String str = HttpClientUtil.doGet2(url, "UTF-8");
- if (str != null) {
- logger.info("http Get request result:" + str);
- } else {
- logger.info("http Get request process fail");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private static void postRequestTest() {
- String url = "http://localhost:8080/SpringMVC/processing";
- Map<String, Object> _params = new HashMap<String, Object>();
- _params.put("name", "zhangshang");
- _params.put("age", 25);
- String str = HttpClientUtil.doPost(url, _params, "UTF-8", true);
- if (str != null) {
- logger.info("http Post request result:" + str);
- } else {
- logger.info("http Post request process fail");
- }
- }
- }
三.HttpClient請求json數據返回json數據
- package com.bijian.study;
- import java.io.IOException;
- import java.net.URLDecoder;
- import net.sf.json.JSONObject;
- import org.apache.http.HttpResponse;
- import org.apache.http.HttpStatus;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.util.EntityUtils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- /**
- * Http請求工具類,發送json返回json
- *
- * 除了要導入json-lib-2.1.jar之外,還必須有其它幾個依賴包:
- * commons-beanutils.jar
- * commons-httpclient.jar
- * commons-lang.jar
- * ezmorph.jar
- * morph-1.0.1.jar
- * 另外,commons-collections.jar也需要導入
- */
- public class HttpRequestUtil {
- private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);
- /**
- * 發送get請求
- * @param url 路徑
- * @return
- */
- public static JSONObject httpGet(String url){
- //get請求返回結果
- JSONObject jsonResult = null;
- try {
- DefaultHttpClient client = new DefaultHttpClient();
- //發送get請求
- HttpGet request = new HttpGet(url);
- HttpResponse response = client.execute(request);
- /**請求發送成功,並得到響應**/
- if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
- /**讀取服務器返回過來的json字符串數據**/
- String strResult = EntityUtils.toString(response.getEntity());
- /**把json字符串轉換成json對象**/
- jsonResult = JSONObject.fromObject(strResult);
- url = URLDecoder.decode(url, "UTF-8");
- } else {
- logger.error("get請求提交失敗:" + url);
- }
- } catch (IOException e) {
- logger.error("get請求提交失敗:" + url, e);
- }
- return jsonResult;
- }
- /**
- * httpPost
- * @param url 路徑
- * @param jsonParam 參數
- * @return
- */
- public static JSONObject httpPost(String url,JSONObject jsonParam){
- return httpPost(url, jsonParam, false);
- }
- /**
- * post請求
- * @param url url地址
- * @param jsonParam 參數
- * @param noNeedResponse 不需要返回結果
- * @return
- */
- public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
- //post請求返回結果
- DefaultHttpClient httpClient = new DefaultHttpClient();
- JSONObject jsonResult = null;
- HttpPost method = new HttpPost(url);
- try {
- if (null != jsonParam) {
- //解決中文亂碼問題
- StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
- entity.setContentEncoding("UTF-8");
- entity.setContentType("application/json");
- method.setEntity(entity);
- }
- HttpResponse result = httpClient.execute(method);
- url = URLDecoder.decode(url, "UTF-8");
- /**請求發送成功,並得到響應**/
- if (result.getStatusLine().getStatusCode() == 200) {
- String str = "";
- try {
- /**讀取服務器返回過來的json字符串數據**/
- str = EntityUtils.toString(result.getEntity());
- if (noNeedResponse) {
- return null;
- }
- /**把json字符串轉換成json對象**/
- jsonResult = JSONObject.fromObject(str);
- } catch (Exception e) {
- logger.error("post請求提交失敗:" + url, e);
- }
- }
- } catch (IOException e) {
- logger.error("post請求提交失敗:" + url, e);
- }
- return jsonResult;
- }
- }
測試類HttpRequestTest.java
- package com.bijian.study;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import net.sf.json.JSONObject;
- import com.bijian.study.dto.UserDTO;
- /**
- * Http請求測試類
- */
- public class HttpRequestTest {
- private static Logger logger = LoggerFactory.getLogger(HttpRequestTest.class);
- public static void main(String[] args) {
- getRequestTest();
- postRequestTest();
- }
- private static void getRequestTest() {
- String url = "http://localhost:8080/SpringMVC/greet?name=lisi";
- JSONObject jsonObject = HttpRequestUtil.httpGet(url);
- if(jsonObject != null) {
- String userName = (String) jsonObject.get("userName");
- logger.info("http Get request process sucess");
- logger.info("userName:" + userName);
- }else {
- logger.info("http Get request process fail");
- }
- }
- private static void postRequestTest() {
- String url = "http://localhost:8080/SpringMVC/process";
- UserDTO userDTO = new UserDTO();
- userDTO.setName("zhangshang");
- userDTO.setAge(25);
- JSONObject jsonParam = JSONObject.fromObject(userDTO);
- JSONObject responseJSONObject = HttpRequestUtil.httpPost(url, jsonParam);
- if(responseJSONObject != null && "SUCCESS".equals(responseJSONObject.get("status"))) {
- JSONObject userStr = (JSONObject) responseJSONObject.get("userDTO");
- userDTO = (UserDTO) JSONObject.toBean(userStr, UserDTO.class);
- logger.info("http Post request process sucess");
- logger.info("userDTO:" + userDTO);
- }else {
- logger.info("http Post request process fail");
- }
- }
- }
完整的工程代碼請下載附件《HttpClient.zip》。
四.補充說明
1.如果會出現異常:java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher,原因是少了JAR包,造成類找不到,除了要導入JSON網站上面下載的json-lib-2.1.jar包之外,還必須有其它幾個依賴包:
- commons-beanutils.jar
- commons-httpclient.jar
- commons-lang.jar
- ezmorph.jar
- morph-1.0.1.jar
2.@responseBody表示該方法的返回結果直接寫入HTTP response body中。一般在異步獲取數據時使用,在使用@RequestMapping后,返回值通常解析為跳轉路徑,加上@responseBody后返回結果不會被解析為跳轉路徑,而是直接寫入HTTP response body中。比如異步獲取json數據,加上@responsebody后,會直接返回json數據。
3.關於HttpClient的其它方面的學習使用,可以參考:http://www.iteblog.com/archives/1379。附件《httpclientutil.zip》就是從這里下載的。
4.在實際使用當中,我們可能需要隨機變換請求數據,甚至隨機請求不同的服務器,可以參考如下方式。
- public static void main(String arg[]) throws Exception {
- while (true) {
- String[] urlArray = {Constant.URL_1, Constant.URL_2};
- int index = new Random().nextInt(2);
- String requestUrl = urlArray[index];
- System.out.println(requestUrl);
- ...
- JSONObject jsonMsg = JSONObject.fromObject(obj);
- String ret = HttpRequestUtil.doPost(requestUrl, jsonMsg);
- System.out.println(ret);
- Thread.sleep(50);
- }
- }
Constant.java
- public class Constant {
- public static final String URL_1 = PropertiesFileUtil.getPropValue("url1", "config");
- public static final String URL_2 = PropertiesFileUtil.getPropValue("url2", "config");
- }
- import java.util.ResourceBundle;
- import org.apache.commons.lang.StringUtils;
- public final class PropertiesFileUtil {
- public static String getPropValue(String keyName, String propsName) {
- ResourceBundle resource = ResourceBundle.getBundle(propsName);
- String value = resource.getString(keyName);
- return value;
- }
- /**
- * 獲取配置文件中keyName對應的value
- */
- public static String getPropValue(String keyName, String propsName, String defaultValue) {
- ResourceBundle resource = ResourceBundle.getBundle(propsName);
- String value = resource.getString(keyName);
- if (StringUtils.isEmpty(value)) {
- value = defaultValue;
- }
- return value;
- }
- }
- url1=http://localhost:8080/SpringMVC/greet?name=lisi
- url2=http://127.0.0.1:8080/SpringMVC/greet?name=zhangshan