简体   繁体   中英

Is it possible to add path segment after query parameter in OkHttp?

I have an http url:

HttpUrl httpurl = new HttpUrl.Builder()
.scheme("https")
.host("www.example.com")
.addQueryParameter("parameter", "p")
.addPathSegment("extrasegment")
.build();

The query parameter always ends up last. How can I enforce the order that I want?

EDIT:

The reason I am trying to achieve this is because I want to be able to access certain endpoints that are formatted like so:

https://host/api/{parameter}/anothersegment

I presume (from the original question) something like the following is desired:

https://www.example.com/?param=p/anothersegment

Taking the URI specification into account which defines this:

scheme ":" hier-part [ "?" query ] [ "#" fragment ]

The url would look something like this:

scheme = https
hier-part = www.example.com/
query = param=p/anothersegment

Which you can achieve like this:

HttpUrl httpurl = new HttpUrl.Builder()
.scheme("https")
.host("www.example.com")
.addEncodedQueryParameter("param", "p/anotersegment")
// Use `EncodedQueryParamter` to prevent escaping the slashes and other special characters. (You need to escape values yourself though)
.build();

From the edit though a guess might be that you want to achieve something like this:

https://www.example.com/foo=bar/baz=xy

Where the foo=bar and baz=xy are just more path segments which you can add with addPathSegment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM