120.OkHttp的Get参数拼接

1. 

缺点:url带问号会出错

/**
 * 拼接Get的Url请求地址
 *
 * @param url
 * @param params
 * @return
 */
private String appendUrl(String url, Map params) {
    if (params == null || params.isEmpty()) {
        return url;
    }

    StringBuilder builder = new StringBuilder(url);
    boolean isFirst = true;
    for (String key : params.keySet()) {
        if (key != null && params.get(key) != null) {
            if (isFirst) {
                isFirst = false;
                builder.append("?");
            } else {
                builder.append("&");
            }
            builder.append(key)
                    .append("=")
                    .append(params.get(key));
        }
    }
    return builder.toString();
}

 2.使用HttpUrl.Builder 组装 URL 地址参数

借鉴:http://netkiller.sourceforge.net/android/HttpUrl.Builder.html

public String getUrl(String url, Map params) {
    HttpUrl.Builder builder = HttpUrl.parse(url).newBuilder();

    if (params != null && params.size() > 0) {
        for (String key : params.keySet()) {
            builder.addQueryParameter(key, (String) params.get(key));
        }
    }
    String newUrl = builder.build().toString();

    return newUrl;
}

 

你可能感兴趣的:(android)