spring+httpClient調用別人服務 – JAVA編程語言程序開發技術文章

首先,在spring的配置需要調用的url,例如:
[java]
<bean id="adManager" class="com.jd.hotel.manager.index.impl.AdManagerImpl"> 
        <property name="adUrl" value="${hotel.ad.url}"/> 
    </bean> 
在Manger調用的時候set註入進來

[java]
private List<GroupProduct> getData() throws Exception{ 
       Map<String, String> paraMap = new HashMap<String, String>(); 
       paraMap.put("action", "max_team_five_city_hotel_team_info"); 
       String result = httpClientUtilManager.executeHttpRequestByGetType(groupProductUrl, paraMap); 
       List<GroupProduct> groupProducts = convertData(result); 
       return groupProducts; 
   } 

executeHttpRequestByGetType方法:
[java]
 /**
     * get方式提交
     *
     * @param url
     * @param keyValueMap
     * @return
     */ 
    public String executeHttpRequestByGetType(String url, Map<String, String> keyValueMap) { 
        HttpClient client = new HttpClient(); 
        StringBuffer sb = new StringBuffer(url); 
        PostMethod postMethod = null; 
        try { 
            //設置請求參數 
            if (keyValueMap != null) { 
                Iterator it = keyValueMap.entrySet().iterator(); 
                if (keyValueMap.size() > 0) { 
                    sb.append("?"); 
                    while (it.hasNext()) { 
                        Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next(); 
                        sb.append(entry.getKey() + "=" + entry.getValue() + "&"); 
                    } 
                    sb.deleteCharAt(sb.length()-1); 
                } 
 
            } 
            postMethod = new PostMethod(sb.toString()); 
            log.debug("query uri ===============" + postMethod.getURI()); 
            postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); 
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk"); 
            //todo:設置超時時間 
            postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 200000); 
            int statusCode = client.executeMethod(postMethod); 
            if (statusCode != HttpStatus.SC_OK) { 
                log.info("request '" + url + "' failed,the status is not 200,status:" + statusCode); 
                return ""; 
            } 
            String responseBody = postMethod.getResponseBodyAsString(); 
            return responseBody; 
        } catch (Exception e) { 
            log.error("發生異常!請檢查網絡和參數", e); 
        } finally { 
            if(postMethod!=null){ 
               postMethod.releaseConnection(); 
            } 
        } 
        return null; 
    } 

convertData方法:
[java]
private List<GroupProduct> convertData(String result) throws Exception{ 
       List<GroupProduct> groupProducts = new ArrayList<GroupProduct>(); 
       if(result==null || "".equals(result)){ 
           return  groupProducts; 
       } 
       try { 
           ArrayList<HashMap> hashMaps = (ArrayList<HashMap>) JSONUtil.deserialize(result); 
           for (HashMap map : hashMaps) { 
               GroupProduct groupProduct = new GroupProduct(); 
               groupProduct.setCityName(map.get("hotel_city").toString()); 
               groupProduct.setDesc(map.get("title").toString()); 
               groupProduct.setOldPrice(map.get("market_price").toString()); 
               groupProduct.setPrice(map.get("team_price").toString()); 
               groupProduct.setImgUrl(map.get("image").toString()); 
               groupProduct.setProductUrl("team-" + map.get("id").toString() + ".html"); 
               groupProduct.setDisCount(countDis(Double.parseDouble(map.get("team_price").toString()), Double.parseDouble(map.get("market_price").toString()))); 
               groupProducts.add(groupProduct); 
           } 
       } catch (Exception e) { 
           log.error("GroupProductManagerImpl convertData error" + e); 
       } 
       return groupProducts; 
 
   } 
 

摘自  tmaic的專欄 

發佈留言