doGet访问封装

for example:

public String getBugMsg(String urlType, int id) {
            
        Map<String, String> params = new HashMap<String, String>();
        params.put("url", urlType);
        params.put("id", Integer.toString(id));
            
            
        String jsonResult = null;
        InputStream is = null;
            
        try {
            is = doGet(aprUrl, params);
            if (is == null) {
                return "";
            }
            jsonResult = getResult(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
            
        if (jsonResult == null) {
            return "";
        }
            
        System.out.println("[getBugMsg] jsonResult: " + jsonResult);
        return jsonResult;
    }
public InputStream doGet(String url, Map<String, String> params) throws IOException {
        StringBuilder sb = new StringBuilder();
                     
        for(Map.Entry<String, String> param : params.entrySet()) {
            sb.append(param.getKey()).append("=").append(param.getValue()).append("&");
        }
                     
        int len = sb.length();
        if (len > 0) {
            sb.deleteCharAt(len - 1);
        }
                     
        String args = sb.toString();
        System.out.println("url args: " + args);
        return doGet(url + "?" + args);
    }
                 
    public InputStream doGet(String urlStr) throws IOException {
                     
        URL url = null;
        try {
            url = new URL(urlStr);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
                     
        HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
        // 为了让访问尽可能像浏览器
        //connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
                     
        // 设置session信息(设置Cookie)
        // 注意,一般的web系统,都会有用户名和密码验证,验证通过后会通过Cookie的方式设置sessionid,
        // 当登录后,发起请求时,需要携带此信息,此时,是通过打开下面的注释即可。
        //String myCookie = "GerritAccount=aSecfaQr028r8-6yxggWFA1QQc0YQFz5";
        /*
        if (sessionId != null) {
            System.out.println("sessionId(2): " + sessionId);
            connection.setRequestProperty("Cookie", "project_name=6; " + sessionId);
        }
        */
                     
        // 设置请求方式为GET
        connection.setRequestMethod("GET");
                     
        connection.connect();
                     
        return connection.getInputStream();
    }

你可能感兴趣的:(doGet访问封装)