1. 程式人生 > >JAVA如何跨專案呼叫介面

JAVA如何跨專案呼叫介面

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());
        }
    }
}