ResourceBundle讀取配置文件與HttpClient結合使用

1 Controller.java

try {
                        HttpClient client = new HttpClient();
                        HttpMethod method = new PostMethod();
                        String host = PropertiesUtils.rtReadProperties("url", "System");
                        method.setPath(host + "/api/settle/getSumthing/" + id);
                        int resp = client.executeMethod(method);
                        if (resp == 200) {
                            byte[] body = method.getResponseBody();
                            JSONObject json = JSONObject.parseObject(new String(body));
                            String code = json.getString("code");
                            if ("000000".equals(code)) {
                                sucCount++;
                            } else {
                                failCount++;
                            }
                        } else {
                            failCount++;
                        }
                    } catch (Exception e) {
                        log.error(e);
                        failCount++;
                    }

 2  PropertiesUtils.java

public class PropertiesUtils {
	public static ResourceBundle res = ResourceBundle.getBundle("application");

	public static String rtReadProperties(String propertiesName, String fileName) {
		String value = null;
		try {
			if (fileName != null) {
				StringBuffer buffer = new StringBuffer(fileName);
				buffer.append(".properties");
				String path = PropertiesUtils.class.getClassLoader()
						.getResource(buffer.toString()).getPath();
				FileInputStream in = new FileInputStream(path);
				Properties properties = new Properties();
				properties.load(in);
				if (propertiesName != null) {
					value = properties.getProperty(propertiesName);
				}
			} else {
				if (propertiesName != null) {
					value = res.getString(propertiesName);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

	
	public static void main(String[] args) {
		String url = PropertiesUtils.rtReadProperties("postUrl","System");
		System.out.println(url);
	}
}

ResourceBundle的使用方式可以先了解下。

非常簡潔的接口調用方式,只需要對方提供請求路徑。上送參數即可。

 

學習是最公平的事!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章