public String load(String url, String query) throws Exception {
URL restURL = new URL(url);
/*
* 此處的urlConnection對象實際上是根據URL的請求協議(此處是http)生成的URLConnection類 的子類HttpURLConnection
*/
HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
//請求方式
conn.setRequestMethod("POST");
//設置是否從httpUrlConnection讀入,默認情況下是true; httpUrlConnection.setDoInput(true);
conn.setDoOutput(true);
//allowUserInteraction 如果為 true,則在允許用戶交互(例如彈出一個驗證對話框)的上下文中對此 URL 進行檢查。
conn.setAllowUserInteraction(false);
PrintStream ps = new PrintStream(conn.getOutputStream());
ps.print(query);
ps.close();
BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line, resultStr = "";
while (null != (line = bReader.readLine())) {
resultStr += line;
}
System.out.println("3412412---" + resultStr);
bReader.close();
return resultStr;
}
public static void main(String[] args) {
try {
APIService restUtil = new APIService();
String resultString = restUtil.load(
"http://**.**.**.**:8079/HouseLizardCloud/Message/ShortMessage",
"mobile=177198****&codeType=2");
} catch (Exception e) {
e.printStackTrace();
System.out.print(e.getMessage());
}
}
}