1. HTTP GET请求
/**
* 向指定URL发送GET方法的请求
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String httpGet(String reqUrl, Map<String, String> headers){
return httpRequest(reqUrl, headers);
}
public static String httpRequest(String reqUrl, Map<String, String> otherHeaders){
URL url;
try {
url = new URL(reqUrl);
HttpURLConnection connection = (HttpURLConnection) ();
String userName = "admin";
String password = "nsfocus";
String auth = userName + ":" + password;
BASE64Encoder enc = new BASE64Encoder();
String encoding = (());
(true);
("Authorization", "Basic " + encoding);
for(Entry<String, String> entry : ()){
((), ());
}
();
BufferedReader reader = new BufferedReader(
new InputStreamReader((),"utf-8"));
StringBuilder sb = new StringBuilder();
String line="";
while ((line = ()) != null){
(line);
}
();
();
return ();
String result = ();
root = (result);
Iterator<JsonNode> rootNode = ();
while(()){
JsonNode c = ();
JsonNode sites = ("site");
String ids = ("id").toString();
id = (1, ()-1);
}
} catch (IOException e) {
("error while getting request: {}", ());
return id;
}
}
2. HTTP POST请求
/**
* 向指定URL发送POST方法的请求
* @param url 发送请求的URL
* @return URL 所代表远程资源的响应结果
*/
public static String httpPost(String reqUrl, String content, Map<String, String> headers){
return httpRequest(reqUrl, "POST", content, headers);
}
public static String httpRequest(String reqUrl, String method, String content,
Map<String, String> headers){
URL url;
try {
url = new URL(reqUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
(true);
(true);
(method);
(false);
(true);
for(Entry<String, String> entry : ()){
((), ());
}
();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
(content);
();
();
BufferedReader reader = new BufferedReader(
new InputStreamReader((),"utf-8"));
StringBuilder sb = new StringBuilder();
String line="";
while ((line = ()) != null){
(line);
}
();
();
return ();
} catch (IOException e) {
("error while posting request: {}", ());
return null;
}
}
3. HTTP PUT请求
public void httpPut(String dst_ip) {
GlobalConfig global = GlobalConfig.getInstance();
String urlStr = global.sncHost + "/devices/1/acl/aclGroups/aclGroup";
String xmlInfo = createXmlInfo(dst_ip);
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(xmlInfo.getBytes("utf-8"));
os.flush();
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
String result = "";
while( (line =br.readLine()) != null ){
result += line;
}
log.info(result);
br.close();
} catch (Exception e) {
log.info("Error in pushing policy now");
e.printStackTrace();
}
}