日期:2014-05-16  浏览次数:20434 次

根据网址,返回JSONObject对象
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.json.JSONException;
import org.json.JSONObject;

/**
  * 根据网址,返回编码方式为utf-8的JSONObject对象
  * 注:只适合请求响应为json格式网址
  * @param src 来源网址
  * @author chitianxiang $22th March, 2012 - 2:44 p.m
  */
static private JSONObject getJsonObj4Utf8(String src) throws Exception {
    return getJsonObj(src, "utf-8");
}
/**
  * 根据网址,返回JSONObject对象
  * 注:只适合请求响应为json格式网址
  * @param src 来源网址
  * @param code 编码方式
  * @author chitianxiang $22th March, 2012 - 2:42 p.m
  */
static private JSONObject getJsonObj(String src, String code) {
    InputStreamReader reader = null;
    BufferedReader in = null;
    try {
        URL url = new URL(src);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(1000);
        reader = new InputStreamReader(connection.getInputStream(), code);
        in = new BufferedReader(reader);
        String line = null; //每行内容
        int lineFlag = 0; //标记: 判断有没有数据
        StringBuffer content = new StringBuffer();
        while ((line = in.readLine()) != null) {
            content.append(line);
            lineFlag++;
        }
        return lineFlag == 0 ? null : new JSONObject(content.toString());
    } catch (SocketTimeoutException e) {
        System.out.println("连接超时!!!");
        return null;
    } catch (JSONException e) {
        System.out.println("网站响应不是json格式,无法转化成JSONObject!!!");
        return null;
    } catch (Exception e) {
        System.out.println("连接网址不对或读取流出现异常!!!");
        return null;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                System.out.println("关闭流出现异常!!!");
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                System.out.println("关闭流出现异常!!!");
            }
        }
    }
} 

//简单使用
//小秘书网菜单http://www.xiaomishu.com/shop/postajax/GetDishList.aspx?pageSize=12&typeId=t1&typeSort=A0&resId=C47E19P46723&version=2
//请求ajax网址
StringBuilder sbSrc = new StringBuilder();
sbSrc.append("http://www.xiaomishu.com/shop/postajax/GetDishList.aspx?pageSize=10");
sbSrc.append("&typeId=" + dataId);
sbSrc.append("&typeSort=A0");
String resId = delEndSeparator(sourceUrl, "/");
sbSrc.append("&resId=" + resId.substring(resId.lastIndexOf("/")));
sbSrc.append("&version=2");
//转换成json对象取出菜单
JSONObject jo = getJsonObj4Utf8(sbSrc.toString());
if (jo == null) {
    continue;
}
JSONObject menu = jo.getJSONObject("items");
Iterator<String> keys = menu.keys();
while (keys.hasNext()) {
    String key = keys.next();
    JSONObject goods= menu.getJSONObject(key);
    String title = goods.get("title").toString();
    String price = goods.get("price").toString();
    String[] goodsInfo = new String[] {title, price};
    goodsInfoLst.add(goodsInfo);
}
goodsInfoMap.put(goodstype, goodsInfoLst);

  /**
	 * 删除符合规则的结束符 
	 * @param obj		等删除对象
	 * @param endWith	结束符
	 * @author chitianxiang $Feb 4th, 2012
	 */
	static private String delEndSeparator(Object obj, String endWith) {
		String tempStr = "";
		if (!(obj instanceof String)) {
			tempStr = obj.toString();
		} else {
			tempStr = (String)obj;
		}
     
      return tempStr.endsWith(endWith) 
				? tempStr.substring(0, tempStr.length() - 1)
				: tempStr;
	}