代码分享第四弹,url生成函数。其实这真的是闲的蛋疼的需求才会用到的函数,将各种形式组织的数据做成带?和&的链接,闲的蛋疼才会用这个,正常都用POST来做,具体的方法可以看我前一篇文章 Android获取网页数据的方法总结 里面有POST的用法。一会儿会放出GET的方法,往下看就是了

对于几个没太大用处的类就不多说啥了,看官随便看看:

/**
 * @param params
 * @return
 */
public static String urlCombiner(Map<string , String> params) {
    if (params != null && !params.isEmpty()) {
        StringBuilder url = new StringBuilder();
        boolean first = true;
        for (String key : params.keySet()) {
            if (first) {
                first = false;
                url.append('?');
            }
            else {
                url.append('&');
            }
            url.append(key + '=' + params.get(key));
        }
        return url.toString();

    }
    return "";
}

/**
 * @param nameValuePairs
 * @return
 */
public static String urlCombiner(ArrayList<namevaluepair> nameValuePairs) {
    if (nameValuePairs != null && !nameValuePairs.isEmpty()) {
        StringBuilder url = new StringBuilder();
        int len = nameValuePairs.size();
        for (int i = 0; i < len; i++) {
            if (i == 0) {
                url.append('?');
            }
            else {
                url.append('&');
            }
            url.append(nameValuePairs.get(i).getName() + '=' + nameValuePairs.get(i).getValue());
        }
        return url.toString();
    }
    return "";
}

/**
 * @param params
 * @return
 */
public static String urlCombiner(Bundle params) {
    if (params == null)
        return "";
    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (String key : params.keySet()) {
        if (first) {
            first = false;
            sb.append("?");
        }
        else {
            sb.append("&");
        }
        sb.append(key + "=" + params.getString(key));
    }
    return sb.toString();
}

下面是GET的函数,随便看下,用的httpget,里面就用了上面三个函数中的某个,见代码。

/**
 * @param nameValuePairs
 * @param url
 * @return
 */
public static InputStream doGet(ArrayList<namevaluepair> nameValuePairs, String url) {
    HttpClient httpclient = new DefaultHttpClient();
    try {
        String target = url + urlCombiner(nameValuePairs);
        HttpGet httpget = new HttpGet(target);
        HttpResponse response = httpclient.execute(httpget);
        if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
            return response.getEntity().getContent();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }/*finally {
        httpclient.getConnectionManager().shutdown();
    }*/
    return null;
}