I'm in doubts am on right way for one of my methods. This one is a compositor of URI
I'm using for my http requests
. It just takes data from a separate static class with final Strings
, merges them together and includes received from the server token where necessary. It happened all URIs
are with token and the only one, authentication, without it. What I've done:
private URI urlComposer(String apiUri, String token) {
URI uri = null;
try {
if(apiUri.equals("POST_AUTH_URL")) {
uri = URIUtils.createURI(null, MyConfig.WEB_SERVER, -1, apiUri, null, null);
return uri;
}
String tmp = apiUri.toString();
String[] array = tmp.split("<token>");
tmp = array[0] + auth.getToken() + array[1];
uri = URIUtils.createURI(null, MyConfig.WEB_SERVER, -1, tmp, null, null);
if (MyConfig.DEBUG) Log.d("Dev", "Constructed url " + uri);
return uri;
} catch (URISyntaxException e) {
if (MyConfig.DEBUG) Log.d("Dev", "urlComposer was unable to construct a URL");
e.printStackTrace();
}
return null;
}
Trying to look in the future I don't like the idea to generate more if/else statements if I would have more special cases like this POST_AUTH_URL
. One one hand I want the only one method to be called to construct a URI, on开发者_JAVA技巧 the other I don't want these ifs
. What shall I do?
If you always set URIs, only different ones, you can use a map:
uriMap.put("POST_AUTH_URL", URIUtils.createURI(null, MyConfig.WEB_SERVER, -1, apiUri, null, null));
You can access this map later:
uri = uriMap.get(apiUri);
You could theoretically create an enum URI_TYPE with method createURI (it is difficult to derive the actual parameters from the provided code snippet). This way you'd simply invoke this method on a specific enum value, which would have its own specific implementation.
Pls refer this and this for more information. Hope it helps.
精彩评论