外部連結POST傳參--HttpURLConnection
訪問外部連結我經常用HttpURLConnection,今天記錄下POST請求方便日後查詢。
public static String send(String post,String url){
HttpURLConnection conn = null;
StringBuffer resultBuffer = null;
OutputStreamWriter osw = null;
BufferedReader br = null;
try {
URL realUrl = new URL(url);
// 開啟和URL之間的連線
conn = (HttpURLConnection) realUrl.openConnection();
// 設定通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("charset", "UTF-8");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
// 傳送POST請求必須設定如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);// post不能使用快取
conn.setRequestMethod("POST");
// 獲取URLConnection物件對應的輸出流
osw = new OutputStreamWriter(conn.getOutputStream());
// 傳送請求引數 //post的引數 xx=xx&yy=yy
osw.write(post);
osw.flush();
// 返回資料
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
}
}
return resultBuffer.toString();
}
測試
public static void main(String[] args){
String url="http://192.168.0.70:8555//main/pcver1/roleList//123";
String post="roleName=NULL&pageNumber=1&pageSize=5";
String rstr=send(post,url);
System.out.println("rstr:\r\n"+rstr);
}
結果