Java傳送http的get、post、put請求
阿新 • • 發佈:2019-01-01
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);
// 開啟和URL之間的連線
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//設定使用者名稱密碼
String userName = "admin" ;
String password = "nsfocus";
String auth = userName + ":" + password;
BASE64Encoder enc = new BASE64Encoder();
String encoding = enc.encode(auth.getBytes());
conn.setDoOutput(true);
// conn.setDoInput(true);
// conn.setUseCaches(false);
// //預設為GET請求
// conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + encoding);
// 設定通用的請求屬性
for(Entry<String, String> entry : otherHeaders.entrySet()){
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
// 建立實際的連線
connection.connect();
// 定義 BufferedReader輸入流來讀取URL的響應
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(),"utf-8"));
StringBuilder sb = new StringBuilder();
String line="";
while ((line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
connection.disconnect();
return sb.toString();
//對返回資料進行解析處理
String result = sb.toString();
root = mapper.readTree(result);
Iterator<JsonNode> rootNode = root.elements();
while(rootNode.hasNext()){
JsonNode c = rootNode.next();
JsonNode sites = c.path("site");
String ids = sites.path("id").toString();
//substring方法,"qiqishuang"去除引號
id = ids.substring(1, ids.length()-1);
}
} catch (IOException e) {
log.error("error while getting request: {}", e.getMessage());
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之間的連線
url = new URL(reqUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
// Read from the connection. Default is true.
connection.setDoInput(true);
// Set the post method. Default is GET
connection.setRequestMethod(method);
// Post cannot use caches
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
for(Entry<String, String> entry : headers.entrySet()){
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
// The URL-encoded contend
out.writeBytes(content);
out.flush();
out.close(); // flush and close
// 定義 BufferedReader輸入流來讀取URL的響應
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(),"utf-8"));
StringBuilder sb = new StringBuilder();
String line="";
while ((line = reader.readLine()) != null){
sb.append(line);
}
reader.close();
connection.disconnect();
return sb.toString();
} catch (IOException e) {
log.error("error while posting request: {}", e.getMessage());
return null;
}
}
3. HTTP PUT請求
public void httpPut(String dst_ip) {
GlobalConfig global = GlobalConfig.getInstance();
String urlStr = global.sncHost + "/devices/1/acl/aclGroups/aclGroup";
//create xml info pushed to controller
String xmlInfo = createXmlInfo(dst_ip);
//establish connection and push policy to snc controller
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();
}
}