原创

java 模拟tomcat manage 登录获得接口信息

@org.junit.Test
public void test() {
String result = "";
Document document = null;//引入org.dom4j包
try {
result = getHtmlContext("http://localhost:8090/manager/status?XML=true", "admin", "admin");
document = DocumentHelper.parseText(result);//将字符串转化为XML的Document
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
System.out.println(document.asXML());
}
/**
* @Description: 获取指定URL的内容
* @param tempurl url地址
* @param username tomcat 管理用户名
* @param password tomcat 管理用户密码
* @return
* @throws IOException
*/
public static String getHtmlContext(String tempurl, String username, String password) throws IOException {
URL url = null;
BufferedReader breader = null;
InputStream is = null;
StringBuffer resultBuffer = new StringBuffer();
try {
url = new URL(tempurl);
String userPassword = username + ":" + password;
String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());//在classpath中添加rt.jar包,在%java_home%/jre/lib/rt.jar

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//重点 解决请求阻塞
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
conn.setRequestProperty("Authorization", "Basic " + encoding);
is = conn.getInputStream();
breader = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = breader.readLine()) != null) {
resultBuffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} finally {
if(breader != null)
breader.close();
if(is != null)
is.close();
}
return resultBuffer.toString();
}
正文到此结束
Loading...