java.net.URISyntaxException: Illegal character in query at index 177

Tags: , ,



I tried to get Azure Usage details via nextLink which is shared by Azure. while i tried to make http request URISyntaxException is occured.

HttpClient httpclient = getHttpClient();
          
URIBuilder uriBuilder=new URIBuilder(url);
HttpGet httpGet = new HttpGet(uriBuilder.build());
HttpResponse httpResponse = httpclient.execute(httpGet);

This is the nextLink url:

“https://management.azure.com/subscriptions/78c50b17-61fd-40cc-819c-4953586c7850/providers/Microsoft.Consumption/usageDetails?api-version=2019-11-01&$filter=properties/usageStart eq ‘2020-07-1’ and properties/usageEnd eq ‘2020-07-30’ &metric=actualcost&$expand=properties/meterDetails,properties/additionalInfo&sessiontoken=15:785628&$skiptoken=827CDTHDWI07C46616C7365730&skiptokenver=v1&id=2d790-d675-45d-89j56-3989w06cca”

I think this is because of characters such as ?, & and ! in my URL. so I tried using:

URLEncoder.encode(myUrl, “UTF-8”);

but after this, I faced protocol exception.

Am I missing something here?

Answer

Your URL contains spaces and single quotes, these should be URL encoded like you tried. However, because you tried to URL-encode the entire URL, you end up with this:

https%3A%2F%2Fmanagement.azure.com%2Fsubscriptions%2F78c50b17-61fd-40cc-819c-4953586c7850%2Fproviders%2FMicrosoft.Consumption%2FusageDetails%3Fapi-version%3D2019-11-01%26%24filter%3Dproperties%2FusageStart+eq+%272020-07-1%27+and+properties%2FusageEnd+eq+%272020-07-30%27+%26metric%3Dactualcost%26%24expand%3Dproperties%2FmeterDetails%2Cproperties%2FadditionalInfo%26sessiontoken%3D15%3A785628%26%24skiptoken%3D827CDTHDWI07C46616C7365730%26skiptokenver%3Dv1%26id%3D2d790-d675-45d-89j56-3989w06cca

Which is not a valid URL. You could simply try using a naive form of String replacement:

myUrl = myUrl.replace(" ", "%20").replace("'", "%27");

If that is not sufficient, you’ll need to reconstruct the URL yourself, and only apply URL-encoding on the query parameter values.



Source: stackoverflow