当你写一段代码很纠结时,不防停下来Google一下,一定有人已经解决了你的烦恼!
一、背景
今天PM提出想给一个URL埋点,统计一下访问来源,需要我在路径上加一个参数fromPage=shop_detail;本来是一个很简单的问题,因为原链接根本没参数,只只需要在url后面加上?fromPage=shop_detail;可想了一下有安全隐患,万一url变了,带了参数怎么办?于是想那我就自己判断是否有参数,再决定加?或/;当我下手写的时候又纠结了,为了这么一点东西要写好几行代码呢,不行,还是得先google 一下,就有了如下结论。
二、 添加parameter的方式
2.1 java.net.URI
通过string 生成URI,再通过URI获取query,再通过query判断是添加&或?; 似乎也挺麻烦……
package urItest;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Created by fuxiangxu on 2017/1/10.
*/
public class URITest {
public static URI appendUri(String uri, String appendQuery) throws URISyntaxException {
URI oldUri = new URI(uri);
String newQuery = oldUri.getQuery();
if (newQuery == null) {
newQuery = appendQuery;
} else {
newQuery += "&" + appendQuery;
}
URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(),
oldUri.getPath(), newQuery, oldUri.getFragment());
return newUri;
}
public static void main(String[] args) throws Exception {
System.out.println(appendUri("http://example.com", "name=John"));
System.out.println(appendUri("http://example.com#fragment", "name=John"));
System.out.println(appendUri("http://example.com?email=john.doe@email.com", "name=John"));
System.out.println(appendUri("http://example.com?email=john.doe@email.com#fragment", "name=John"));
}
}
2.2 javax.ws.rs.core.UriBuilder
package urItest;
import javax.ws.rs.core.UriBuilder;
import java.net.URISyntaxException;
/**
* Created by fuxiangxu on 2017/1/10.
*/
public class URIBuilderTest {
public static void main(String[] args) throws URISyntaxException {
System.out.println(UriBuilder.fromUri("http://example.com").queryParam("name", "john").build().toString());
System.out.println(UriBuilder.fromUri("http://example.com?email=john.doe@email.com").queryParam("name", "john").build().toString());
}
}
2.3 org.apache.http.client.utils.URIBuilder
package urItest;
import org.apache.http.client.utils.URIBuilder;
import java.net.URISyntaxException;
/**
* Created by fuxiangxu on 2017/1/10.
*/
public class URIBuilderTest {
public static void main(String[] args) throws URISyntaxException {
System.out.println(new URIBuilder("http://example.com").addParameter("name", "john").build().toString());
System.out.println(new URIBuilder("http://example.com?email=john.doe@email.com").addParameter("name", "john").build().toString());
}
}
2.4 org.springframework.web.util.UriComponentsBuilder (建议)
package urItest;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URISyntaxException;
/**
* Created by fuxiangxu on 2017/1/10.
*/
public class URIBuilderTest {
public static void main(String[] args) throws URISyntaxException {
System.out.println(UriComponentsBuilder.fromUriString("http://example.com").queryParam("name", "john").build().toString());
System.out.println(UriComponentsBuilder.fromUriString("http://example.com?email=john.doe@email.com").queryParam("name", "john").build().toString());
}
}