折腾:
【未解决】Java给OkHttp加cookie出错:Cannot resolve symbol setCookiePolicy和Unknown class CookiePolicy.ACCEPT_ALL
期间,需要去把一个user-agent字符串:
public static String UserAgent_Mac_Chrome = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36";
优化改造为更加完整的写法,变成字符串的枚举
java string enum
【总结】
最后用代码:
// public static String UserAgent_Mac_Chrome = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"; public enum UserAgent { MAC_CHROME("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"), MAC_SAFARI("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15") ; private String text; /** * @param text */ UserAgent(final String text) { this.text = text; } public String getText() { return this.text; } /* (non-Javadoc) * @see java.lang.Enum#toString() */ @Override public String toString() { return this.getText(); } public static UserAgent fromString(String text) { for (UserAgent eachUaValue : UserAgent.values()) { if (eachUaValue.text.equalsIgnoreCase(text)) { return eachUaValue; } } return null; } } }
调用:
.header("User-Agent", CrifanUtil.UserAgent.MAC_CHROME.getText())
即可实现:此处的字符串的枚举
且还支持从字符串中生成枚举值
以及获取到枚举值的字符串。
转载请注明:在路上 » 【已解决】Java中如何实现字符串的枚举