2017-04-06 72 views
0

我正在製作一個使用java swing的小型字典類應用程序。我正在使用牛津字典API。有沒有什麼辦法可以在不使用servelets和所有高級java概念的情況下在java中進行簡單的ajax請求。正如在android中我們使用http url連接來完成這項工作。我搜索了很多關於這個工作的信息,但是我找不到解決方案,因爲每個頁面都使用servelets顯示結果。但我知道單獨的核心java。如果有可能使ajax調用沒有servelts請幫助我...在此先感謝...如何從獨立的Java應用程序進行http調用

回答

1

使用HttpURLConnection類使http調用。

如果您需要更多的幫助,然後去爲Java的官方文檔站點Here

public class JavaHttpUrlConnectionReader { 
    public static void main(String[] args) throws IOException{ 
     String results = doHttpUrlConnectionAction("https://your.url.com/", "GET"); 
     System.out.println(results); 
    } 
    public static String doHttpUrlConnectionAction(String desiredUrl, String requestType) throws IOException { 
     BufferedReader reader = null; 
     StringBuilder stringBuilder; 
     try { 
      HttpURLConnection connection = (HttpURLConnection) new URL(desiredUrl).openConnection(); 
      connection.setRequestMethod(requestType);// Can be "GET","POST","DELETE",etc 
      connection.setReadTimeout(3 * 1000); 
      connection.connect();// Make call 
      reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));// Reading Responce 
      stringBuilder = new StringBuilder(); 

      String line; 
      while ((line = reader.readLine()) != null) { 
       stringBuilder.append(line).append("\n"); 
      } 
      return stringBuilder.toString(); 
     } catch (IOException e) { 
      throw new IOException("Problam in connection : ", e); 
     } finally { 
      if (reader != null) { 
       try { 
        reader.close(); 
       } catch (IOException ioe) { 
        throw new IOException("Problam in closing reader : ", ioe); 
       } 
      } 
     } 
    } 
} 

這將撥打電話,並給予響應,返回的字符串。如果你想POST調用需要做一些額外的爲:

try{ 
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); 
    wr.write(postParam.getBytes()); 
} catch(IOException e){ 
} 

注:這裏postParamString型與價值的財產以後像"someId=156422&someAnotherId=32651"

,並把這個porson befor connection.connect()聲明。

+0

非常感謝... – bharath

+0

歡迎... :)) –