zoukankan      html  css  js  c++  java
  • JAVA发送HttpClient请求及接收请求完整代码实例

    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中获取到。

    Java代码  收藏代码
    1. @Controller  
    2. public class HelloController {  
    3.   
    4.     private static Logger logger = LoggerFactory.getLogger(HelloController.class);  
    5.   
    6.     @Autowired  
    7.     private HelloService helloService;  
    8.   
    9.     @RequestMapping("/greeting")  
    10.     public ModelAndView greeting(@RequestParam(value = "name", defaultValue = "World") String name) {  
    11.   
    12.         Map<String, Object> map = new HashMap<String, Object>();  
    13.         try {  
    14.             //由于浏览器会把中文直接换成ISO-8859-1编码格式,如果用户在地址打入中文,需要进行如下转换处理  
    15.             String tempName = new String(name.getBytes("ISO-8859-1"), "utf-8");  
    16.   
    17.             logger.trace("tempName:" + tempName);  
    18.             logger.info(tempName);  
    19.   
    20.             String userName = helloService.processService(tempName);  
    21.   
    22.             map.put("userName", userName);  
    23.               
    24.             logger.trace("运行结果:" + map);  
    25.         } catch (UnsupportedEncodingException e) {  
    26.             logger.error("HelloController greeting方法发生UnsupportedEncodingException异常:" + e);  
    27.         } catch (Exception e) {  
    28.             logger.error("HelloController greeting方法发生Exception异常:" + e);  
    29.         }  
    30.         return new ModelAndView("/hello", map);  
    31.     }  
    32.       
    33.     @RequestMapping(value="/processing", method = RequestMethod.POST)  
    34.     public ModelAndView processing(HttpServletRequest request, HttpServletResponse response) {  
    35.   
    36.         Enumeration en = request.getParameterNames();  
    37.         while (en.hasMoreElements()) {  
    38.             String paramName = (String) en.nextElement();  
    39.             String paramValue = request.getParameter(paramName);  
    40.         }  
    41.           
    42.         String name = request.getParameter("name");  
    43.         String age = request.getParameter("age");  
    44.           
    45.         UserDTO userDTO = new UserDTO();  
    46.         userDTO.setName(name);  
    47.         userDTO.setAge(Integer.valueOf(age));  
    48.           
    49.         logger.info("process param is :{}" + userDTO);  
    50.           
    51.         Map<String, Object> map = new HashMap<String, Object>();  
    52.         try {  
    53.             userDTO = helloService.processService(userDTO);  
    54.             //返回请求结果  
    55.             map.put("name", userDTO.getName());  
    56.             map.put("age", userDTO.getAge());  
    57.         } catch (Exception e) {  
    58.             logger.info("请求处理异常:" + e);  
    59.         }  
    60.         return new ModelAndView("/user", map);  
    61.     }  
    62.   
    63.     /** 
    64.      * @responseBody表示该方法的返回结果直接写入HTTP response body中 
    65.      * 一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径 
    66.      * 加上@responseBody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。 
    67.      * 比如异步获取json数据,加上@responsebody后,会直接返回json数据。 
    68.      */  
    69.     @ResponseBody  
    70.     @RequestMapping(value="/greet",method = RequestMethod.GET)  
    71.     public Map<String, Object> greet(HttpServletRequest request, HttpServletResponse response,   
    72.             @RequestParam(value = "name", defaultValue = "World") String name) {  
    73.   
    74.         Map<String, Object> map = null;  
    75.         try {  
    76.             //由于浏览器会把中文直接换成ISO-8859-1编码格式,如果用户在地址打入中文,需要进行如下转换处理  
    77.             String tempName = new String(name.getBytes("ISO-8859-1"), "utf-8");  
    78.               
    79.             logger.trace("tempName:" + tempName);  
    80.             logger.info(tempName);  
    81.   
    82.             String userName = helloService.processService(tempName);  
    83.   
    84.             map = new HashMap<String, Object>();  
    85.             map.put("userName", userName);  
    86.               
    87.             logger.trace("运行结果:" + map);  
    88.         } catch (UnsupportedEncodingException e) {  
    89.             logger.error("HelloController greet方法发生UnsupportedEncodingException异常:" + e);  
    90.         } catch (Exception e) {  
    91.             logger.error("HelloController greet方法发生Exception异常:" + e);  
    92.         }  
    93.         return map;  
    94.     }  
    95.   
    96.     @ResponseBody  
    97.     @RequestMapping(value="/process",method = RequestMethod.POST)  
    98.     public String process(HttpServletRequest request, @RequestBody String requestBody) {  
    99.   
    100.         logger.info("process param is :{}" + requestBody);  
    101.         JSONObject result = new JSONObject();  
    102.         try {  
    103.             JSONObject jsonObject = JSONObject.fromObject(requestBody);  
    104.             UserDTO userDTO = (UserDTO) JSONObject.toBean(jsonObject, UserDTO.class);  
    105.   
    106.             userDTO = helloService.processService(userDTO);  
    107.   
    108.             //返回请求结果  
    109.             result.put("status""SUCCESS");  
    110.             result.put("userDTO", userDTO);  
    111.         } catch (Exception e) {  
    112.             logger.info("请求处理异常! params is:{}", requestBody);  
    113.             result.put("status""FAIL");  
    114.         }  
    115.         return result.toString();  
    116.     }  
    117. }  

     

    二.HttpClient请求普通的表单数据,返回HTML页面

    Java代码  收藏代码
    1. package com.bijian.study;  
    2.   
    3. import java.io.BufferedReader;  
    4. import java.io.IOException;  
    5. import java.io.InputStreamReader;  
    6. import java.util.Map;  
    7.   
    8. import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;  
    9. import org.apache.commons.httpclient.Header;  
    10. import org.apache.commons.httpclient.HttpClient;  
    11. import org.apache.commons.httpclient.HttpException;  
    12. import org.apache.commons.httpclient.HttpMethod;  
    13. import org.apache.commons.httpclient.HttpStatus;  
    14. import org.apache.commons.httpclient.NameValuePair;  
    15. import org.apache.commons.httpclient.methods.GetMethod;  
    16. import org.apache.commons.httpclient.methods.PostMethod;  
    17. import org.apache.commons.httpclient.params.HttpMethodParams;  
    18. import org.apache.http.client.methods.HttpPost;  
    19.   
    20. /** 
    21.  * Http请求工具类 
    22.  * 请求的是普通的表单数据,返回HTML页面 
    23.  *  
    24.  * 需要导入commons-codec-1.3.jar 
    25.  */  
    26. public class HttpClientUtil {  
    27.   
    28.     /** 
    29.      * httpClient的get请求方式 
    30.      *  
    31.      * @param url 
    32.      * @param charset 
    33.      * @return 
    34.      * @throws Exception 
    35.      */  
    36.     public static String doGet(String url, String charset) throws Exception {  
    37.   
    38.         HttpClient client = new HttpClient();  
    39.         GetMethod method = new GetMethod(url);  
    40.   
    41.         if (null == url || !url.startsWith("http")) {  
    42.             throw new Exception("请求地址格式不对");  
    43.         }  
    44.         // 设置请求的编码方式  
    45.         if (null != charset) {  
    46.             method.addRequestHeader("Content-Type""application/x-www-form-urlencoded; charset=" + charset);  
    47.         } else {  
    48.             method.addRequestHeader("Content-Type""application/x-www-form-urlencoded; charset=" + "utf-8");  
    49.         }  
    50.         int statusCode = client.executeMethod(method);  
    51.   
    52.         if (statusCode != HttpStatus.SC_OK) {// 打印服务器返回的状态  
    53.             System.out.println("Method failed: " + method.getStatusLine());  
    54.         }  
    55.         // 返回响应消息  
    56.         byte[] responseBody = method.getResponseBodyAsString().getBytes(method.getResponseCharSet());  
    57.         // 在返回响应消息使用编码(utf-8或gb2312)  
    58.         String response = new String(responseBody, "utf-8");  
    59.         System.out.println("------------------response:" + response);  
    60.         // 释放连接  
    61.         method.releaseConnection();  
    62.         return response;  
    63.     }  
    64.   
    65.     /** 
    66.      * httpClient的get请求方式2 
    67.      *  
    68.      * @param url 
    69.      * @param charset 
    70.      * @return 
    71.      * @throws Exception 
    72.      */  
    73.     public static String doGet2(String url, String charset) throws Exception {  
    74.         /* 
    75.          * 使用 GetMethod 来访问一个 URL 对应的网页,实现步骤: 1:生成一个 HttpClinet 对象并设置相应的参数。 
    76.          * 2:生成一个 GetMethod 对象并设置响应的参数。 3:用 HttpClinet 生成的对象来执行 GetMethod 生成的Get 
    77.          * 方法。 4:处理响应状态码。 5:若响应正常,处理 HTTP 响应内容。 6:释放连接。 
    78.          */  
    79.         /* 1 生成 HttpClinet 对象并设置参数 */  
    80.         HttpClient httpClient = new HttpClient();  
    81.         // 设置 Http 连接超时为5秒  
    82.         httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);  
    83.   
    84.         /* 2 生成 GetMethod 对象并设置参数 */  
    85.         GetMethod getMethod = new GetMethod(url);  
    86.         // 设置 get 请求超时为 5 秒  
    87.         getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);  
    88.         // 设置请求重试处理,用的是默认的重试处理:请求三次  
    89.         getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());  
    90.         String response = "";  
    91.         /* 3 执行 HTTP GET 请求 */  
    92.         try {  
    93.             int statusCode = httpClient.executeMethod(getMethod);  
    94.             /* 4 判断访问的状态码 */  
    95.             if (statusCode != HttpStatus.SC_OK) {  
    96.                 System.err.println("Method failed: " + getMethod.getStatusLine());  
    97.             }  
    98.             /* 5 处理 HTTP 响应内容 */  
    99.             // HTTP响应头部信息,这里简单打印  
    100.             Header[] headers = getMethod.getResponseHeaders();  
    101.             for (Header h : headers)  
    102.                 System.out.println(h.getName() + "------------ " + h.getValue());  
    103.             // 读取 HTTP 响应内容,这里简单打印网页内容  
    104.             byte[] responseBody = getMethod.getResponseBody();// 读取为字节数组  
    105.             response = new String(responseBody, charset);  
    106.             System.out.println("----------response:" + response);  
    107.             // 读取为 InputStream,在网页内容数据量大时候推荐使用  
    108.             // InputStream response = getMethod.getResponseBodyAsStream();  
    109.   
    110.         } catch (HttpException e) {  
    111.             // 发生致命的异常,可能是协议不对或者返回的内容有问题  
    112.             System.out.println("Please check your provided http address!");  
    113.             e.printStackTrace();  
    114.         } catch (IOException e) {  
    115.             // 发生网络异常  
    116.             e.printStackTrace();  
    117.         } finally {  
    118.             /* 6 .释放连接 */  
    119.             getMethod.releaseConnection();  
    120.         }  
    121.         return response;  
    122.     }  
    123.   
    124.     /** 
    125.      * 执行一个HTTP POST请求,返回请求响应的HTML 
    126.      *  
    127.      * @param url  请求的URL地址 
    128.      * @param params  请求的查询参数,可以为null 
    129.      * @param charset 字符集 
    130.      * @param pretty 是否美化 
    131.      * @return 返回请求响应的HTML 
    132.      */  
    133.     public static String doPost(String url, Map<String, Object> _params, String charset, boolean pretty) {  
    134.           
    135.         StringBuffer response = new StringBuffer();  
    136.         HttpClient client = new HttpClient();  
    137.         PostMethod method = new PostMethod(url);  
    138.           
    139.         // 设置Http Post数据  
    140.         if (_params != null) {  
    141.             for (Map.Entry<String, Object> entry : _params.entrySet()) {  
    142.                 method.setParameter(entry.getKey(), String.valueOf(entry.getValue()));  
    143.             }  
    144.         }  
    145.           
    146.         // 设置Http Post数据  方法二  
    147. //        if(_params != null) {  
    148. //            NameValuePair[] pairs = new NameValuePair[_params.size()];//纯参数了,键值对  
    149. //            int i = 0;  
    150. //            for (Map.Entry<String, Object> entry : _params.entrySet()) {  
    151. //                pairs[i] = new NameValuePair(entry.getKey(), String.valueOf(entry.getValue()));  
    152. //                i++;  
    153. //            }  
    154. //            method.addParameters(pairs);  
    155. //        }  
    156.           
    157.         try {  
    158.             client.executeMethod(method);  
    159.             if (method.getStatusCode() == HttpStatus.SC_OK) {  
    160.                 // 读取为 InputStream,在网页内容数据量大时候推荐使用  
    161.                 BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(),  
    162.                         charset));  
    163.                 String line;  
    164.                 while ((line = reader.readLine()) != null) {  
    165.                     if (pretty)  
    166.                         response.append(line).append(System.getProperty("line.separator"));  
    167.                     else  
    168.                         response.append(line);  
    169.                 }  
    170.                 reader.close();  
    171.             }  
    172.         } catch (IOException e) {  
    173.             System.out.println("执行HTTP Post请求" + url + "时,发生异常!");  
    174.             e.printStackTrace();  
    175.         } finally {  
    176.             method.releaseConnection();  
    177.         }  
    178.         System.out.println("--------------------" + response.toString());  
    179.         return response.toString();  
    180.     }  
    181. }  

            测试类HttpClientTest.java

    Java代码  收藏代码
    1. package com.bijian.study;  
    2.   
    3. import java.util.HashMap;  
    4. import java.util.Map;  
    5.   
    6. import org.slf4j.Logger;  
    7. import org.slf4j.LoggerFactory;  
    8.   
    9. public class HttpClientTest {  
    10.   
    11.     private static Logger logger = LoggerFactory.getLogger(HttpRequestTest.class);  
    12.   
    13.     public static void main(String[] args) {  
    14.   
    15.         getRequestTest();  
    16.         getRequestTest2();  
    17.         postRequestTest();  
    18.     }  
    19.   
    20.     private static void getRequestTest() {  
    21.   
    22.         String url = "http://localhost:8080/SpringMVC/greeting?name=lisi";  
    23.         try {  
    24.             String str = HttpClientUtil.doGet(url, "UTF-8");  
    25.             if (str != null) {  
    26.                 logger.info("http Get request result:" + str);  
    27.             } else {  
    28.                 logger.info("http Get request process fail");  
    29.             }  
    30.         } catch (Exception e) {  
    31.             e.printStackTrace();  
    32.         }  
    33.     }  
    34.   
    35.     private static void getRequestTest2() {  
    36.   
    37.         String url = "http://localhost:8080/SpringMVC/greeting?name=lisi";  
    38.         try {  
    39.             String str = HttpClientUtil.doGet2(url, "UTF-8");  
    40.             if (str != null) {  
    41.                 logger.info("http Get request result:" + str);  
    42.             } else {  
    43.                 logger.info("http Get request process fail");  
    44.             }  
    45.         } catch (Exception e) {  
    46.             e.printStackTrace();  
    47.         }  
    48.     }  
    49.   
    50.     private static void postRequestTest() {  
    51.   
    52.         String url = "http://localhost:8080/SpringMVC/processing";  
    53.   
    54.         Map<String, Object> _params = new HashMap<String, Object>();  
    55.         _params.put("name""zhangshang");  
    56.         _params.put("age"25);  
    57.         String str = HttpClientUtil.doPost(url, _params, "UTF-8"true);  
    58.         if (str != null) {  
    59.             logger.info("http Post request result:" + str);  
    60.         } else {  
    61.             logger.info("http Post request process fail");  
    62.         }  
    63.     }  
    64. }  

     

    三.HttpClient请求json数据返回json数据

    Java代码  收藏代码
    1. package com.bijian.study;  
    2.   
    3. import java.io.IOException;  
    4. import java.net.URLDecoder;  
    5.   
    6. import net.sf.json.JSONObject;  
    7.   
    8. import org.apache.http.HttpResponse;  
    9. import org.apache.http.HttpStatus;  
    10. import org.apache.http.client.methods.HttpGet;  
    11. import org.apache.http.client.methods.HttpPost;  
    12. import org.apache.http.entity.StringEntity;  
    13. import org.apache.http.impl.client.DefaultHttpClient;  
    14. import org.apache.http.util.EntityUtils;  
    15. import org.slf4j.Logger;  
    16. import org.slf4j.LoggerFactory;  
    17.   
    18. /** 
    19.  * Http请求工具类,发送json返回json 
    20.  *  
    21.  * 除了要导入json-lib-2.1.jar之外,还必须有其它几个依赖包: 
    22.  * commons-beanutils.jar 
    23.  * commons-httpclient.jar 
    24.  * commons-lang.jar 
    25.  * ezmorph.jar 
    26.  * morph-1.0.1.jar 
    27.  * 另外,commons-collections.jar也需要导入 
    28.  */  
    29. public class HttpRequestUtil {  
    30.       
    31.     private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);      
    32.   
    33.     /** 
    34.      * 发送get请求 
    35.      * @param url 路径 
    36.      * @return 
    37.      */  
    38.     public static JSONObject httpGet(String url){  
    39.           
    40.         //get请求返回结果  
    41.         JSONObject jsonResult = null;  
    42.         try {  
    43.             DefaultHttpClient client = new DefaultHttpClient();  
    44.             //发送get请求  
    45.             HttpGet request = new HttpGet(url);  
    46.             HttpResponse response = client.execute(request);  
    47.   
    48.             /**请求发送成功,并得到响应**/  
    49.             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
    50.                 /**读取服务器返回过来的json字符串数据**/  
    51.                 String strResult = EntityUtils.toString(response.getEntity());  
    52.                 /**把json字符串转换成json对象**/  
    53.                 jsonResult = JSONObject.fromObject(strResult);  
    54.                 url = URLDecoder.decode(url, "UTF-8");  
    55.             } else {  
    56.                 logger.error("get请求提交失败:" + url);  
    57.             }  
    58.         } catch (IOException e) {  
    59.             logger.error("get请求提交失败:" + url, e);  
    60.         }  
    61.         return jsonResult;  
    62.     }  
    63.       
    64.     /** 
    65.      * httpPost 
    66.      * @param url  路径 
    67.      * @param jsonParam 参数 
    68.      * @return 
    69.      */  
    70.     public static JSONObject httpPost(String url,JSONObject jsonParam){  
    71.         return httpPost(url, jsonParam, false);  
    72.     }  
    73.   
    74.     /** 
    75.      * post请求 
    76.      * @param url         url地址 
    77.      * @param jsonParam     参数 
    78.      * @param noNeedResponse    不需要返回结果 
    79.      * @return 
    80.      */  
    81.     public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){  
    82.           
    83.         //post请求返回结果  
    84.         DefaultHttpClient httpClient = new DefaultHttpClient();  
    85.         JSONObject jsonResult = null;  
    86.         HttpPost method = new HttpPost(url);  
    87.         try {  
    88.             if (null != jsonParam) {  
    89.                 //解决中文乱码问题  
    90.                 StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");  
    91.                 entity.setContentEncoding("UTF-8");  
    92.                 entity.setContentType("application/json");  
    93.                 method.setEntity(entity);  
    94.             }  
    95.             HttpResponse result = httpClient.execute(method);  
    96.             url = URLDecoder.decode(url, "UTF-8");  
    97.             /**请求发送成功,并得到响应**/  
    98.             if (result.getStatusLine().getStatusCode() == 200) {  
    99.                 String str = "";  
    100.                 try {  
    101.                     /**读取服务器返回过来的json字符串数据**/  
    102.                     str = EntityUtils.toString(result.getEntity());  
    103.                     if (noNeedResponse) {  
    104.                         return null;  
    105.                     }  
    106.                     /**把json字符串转换成json对象**/  
    107.                     jsonResult = JSONObject.fromObject(str);  
    108.                 } catch (Exception e) {  
    109.                     logger.error("post请求提交失败:" + url, e);  
    110.                 }  
    111.             }  
    112.         } catch (IOException e) {  
    113.             logger.error("post请求提交失败:" + url, e);  
    114.         }  
    115.         return jsonResult;  
    116.     }  
    117. }  

            测试类HttpRequestTest.java

    Java代码  收藏代码
    1. package com.bijian.study;  
    2.   
    3. import org.slf4j.Logger;  
    4. import org.slf4j.LoggerFactory;  
    5.   
    6. import net.sf.json.JSONObject;  
    7.   
    8. import com.bijian.study.dto.UserDTO;  
    9.   
    10. /** 
    11.  * Http请求测试类 
    12.  */  
    13. public class HttpRequestTest {  
    14.   
    15.     private static Logger logger = LoggerFactory.getLogger(HttpRequestTest.class);  
    16.       
    17.     public static void main(String[] args) {  
    18.           
    19.         getRequestTest();  
    20.         postRequestTest();  
    21.     }  
    22.   
    23.     private static void getRequestTest() {  
    24.           
    25.         String url = "http://localhost:8080/SpringMVC/greet?name=lisi";  
    26.         JSONObject jsonObject = HttpRequestUtil.httpGet(url);  
    27.         if(jsonObject != null) {  
    28.             String userName = (String) jsonObject.get("userName");  
    29.             logger.info("http Get request process sucess");  
    30.             logger.info("userName:" + userName);  
    31.         }else {  
    32.             logger.info("http Get request process fail");  
    33.         }  
    34.     }  
    35.   
    36.     private static void postRequestTest() {  
    37.           
    38.         String url = "http://localhost:8080/SpringMVC/process";  
    39.           
    40.         UserDTO userDTO = new UserDTO();  
    41.         userDTO.setName("zhangshang");  
    42.         userDTO.setAge(25);  
    43.         JSONObject jsonParam = JSONObject.fromObject(userDTO);  
    44.           
    45.         JSONObject responseJSONObject = HttpRequestUtil.httpPost(url, jsonParam);  
    46.         if(responseJSONObject != null && "SUCCESS".equals(responseJSONObject.get("status"))) {  
    47.             JSONObject userStr = (JSONObject) responseJSONObject.get("userDTO");  
    48.             userDTO = (UserDTO) JSONObject.toBean(userStr, UserDTO.class);  
    49.               
    50.             logger.info("http Post request process sucess");  
    51.             logger.info("userDTO:" + userDTO);  
    52.         }else {  
    53.             logger.info("http Post request process fail");  
    54.         }  
    55.     }  
    56. }  

            完整的工程代码请下载附件《HttpClient.zip》。

     

    四.补充说明

            1.如果会出现异常:java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher,原因是少了JAR包,造成类找不到,除了要导入JSON网站上面下载的json-lib-2.1.jar包之外,还必须有其它几个依赖包:

    Text代码  收藏代码
    1. commons-beanutils.jar  
    2. commons-httpclient.jar  
    3. commons-lang.jar  
    4. ezmorph.jar  
    5. 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.在实际使用当中,我们可能需要随机变换请求数据,甚至随机请求不同的服务器,可以参考如下方式。

    Java代码  收藏代码
    1. public static void main(String arg[]) throws Exception {  
    2.     while (true) {  
    3.         String[] urlArray = {Constant.URL_1, Constant.URL_2};  
    4.         int index = new Random().nextInt(2);  
    5.         String requestUrl = urlArray[index];  
    6.         System.out.println(requestUrl);  
    7.           
    8.         ...  
    9.           
    10.         JSONObject jsonMsg = JSONObject.fromObject(obj);  
    11.           
    12.         String ret = HttpRequestUtil.doPost(requestUrl, jsonMsg);  
    13.         System.out.println(ret);  
    14.         Thread.sleep(50);  
    15.     }  
    16. }  

    Constant.java

    Java代码  收藏代码
    1. public class Constant {  
    2.   
    3.     public static final String URL_1 = PropertiesFileUtil.getPropValue("url1""config");  
    4.     public static final String URL_2 = PropertiesFileUtil.getPropValue("url2""config");  
    5. }  
    PropertiesFileUtil.java
    Java代码  收藏代码
    1. import java.util.ResourceBundle;  
    2.   
    3. import org.apache.commons.lang.StringUtils;  
    4.   
    5. public final class PropertiesFileUtil {  
    6.   
    7.     public static String getPropValue(String keyName, String propsName) {  
    8.   
    9.         ResourceBundle resource = ResourceBundle.getBundle(propsName);  
    10.         String value = resource.getString(keyName);  
    11.         return value;  
    12.     }  
    13.   
    14.     /** 
    15.      * 获取配置文件中keyName对应的value 
    16.      */  
    17.     public static String getPropValue(String keyName, String propsName, String defaultValue) {  
    18.   
    19.         ResourceBundle resource = ResourceBundle.getBundle(propsName);  
    20.         String value = resource.getString(keyName);  
    21.         if (StringUtils.isEmpty(value)) {  
    22.             value = defaultValue;  
    23.         }  
    24.         return value;  
    25.     }  
    26. }  
    config.properties
    Java代码  收藏代码
    1. url1=http://localhost:8080/SpringMVC/greet?name=lisi  
    2. url2=http://127.0.0.1:8080/SpringMVC/greet?name=zhangshan  
  • 相关阅读:
    17963 完美数
    17086 字典序的全排列
    17082 两个有序数序列中找第k小(优先做)
    11087 统计逆序对(优先做)
    8594 有重复元素的排列问题(优先做)
    11076 浮点数的分数表达(优先做)
    9715 相邻最大矩形面积
    剑指offer----替换空格
    [IIS][ASP.NET]“拒绝访问临时目录”的解决方法
    windows 2003端口80system进程占用的情况
  • 原文地址:https://www.cnblogs.com/mmzhang/p/8001706.html
Copyright © 2011-2022 走看看