2016-12-06 42 views
0

我正在與一些其他API進行集成,我需要調用它們的URL來接收數據。RestApi發送請求到特定的URL

我只是想知道是否有可能使用REST Web服務將映射到該特定的URL而不是本地的,然後我將寫入將映射到這些調用的客戶端。

例如:

@Path("/URL") 
public class MessageRestService { 

@GET 
@Path("/{param}") 
public Response printMessage(@PathParam("param") String msg) { 

    String result = "Restful example : " + msg; 

    return Response.status(200).entity(result).build(); 

    } 

} 

我不能讓從例如使用AngularJs客戶端直接API調用,因爲我得到這個錯誤:

Response to preflight request doesn't pass access control check: No 'Access-  Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 400. 

我確實發現代碼樣本直API調用來自java的URL,但它看起來很凌亂,尤其是當您需要爲很多API調用創建它時:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 

public class Connection { 

    public static void main(String[] args) { 

      try { 

      URL url = new URL("INSERT URL HERE"); 
      HttpURLConnection conn = (HttpURLConnection)  url.openConnection(); 

      conn.setDoOutput(true); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Content-Type", "application/json"); 


     String messageToPost = "POST"; 

     OutputStream os = conn.getOutputStream(); 
     os.write(input.getBytes()); 
     os.flush(); 

     conn.connect(); 



     BufferedReader br = new BufferedReader(new InputStreamReader(
       (conn.getInputStream()))); 

     String output; 
     System.out.println("Output from Server .... \n"); 
     while ((output = br.readLine()) != null) { 
      System.out.println(output); 
     } 

     conn.disconnect(); 

     } catch (MalformedURLException e) { 

     e.printStackTrace(); 

     } catch (IOException e) { 

     e.printStackTrace(); 

    } 

    } 

} 

回答

0

您正面臨同源策略問題。

這是因爲您的客戶端(Web瀏覽器)應用程序是從服務器A獲取的,而它嘗試與服務器B上的數據進行交互。

  • 服務器-A是無論您從何處獲取應用程序(在其Web瀏覽器上向用戶顯示之前)。
  • 服務器-B爲localhost,你的模擬服務被部署到

出於安全原因,默認情況下,唯一的代碼從服務器-B原產可以談話到服務器B(過度簡化一點位)。這是爲了防止服務器A的惡意代碼劫持來自服務器B的合法應用程序,並誘騙它處理用戶背後的服務器B上的數據。

爲了解決這個問題,如果服務器A的合法應用程序需要與服務器B交談,服務器B必須明確地允許它。爲此,您需要實施CORS(跨源資源共享) - 嘗試使用Google搜索,您會發現很多解釋如何執行此操作的資源。 https://www.html5rocks.com/en/tutorials/cors/也是一個很好的起點。然而,由於你的Server-B/localhost服務只是在開發和測試過程中使用的一個模擬服務,如果你的應用程序足夠簡單,那麼你可能會忽略模擬服務,只需將下面的HTTP頭添加到它的所有響應中:

Access-Control-Allow-Origin:* 
Access-Control-Allow-Headers:Keep-Alive,User-Agent,Content-Type,Accept [enhance with whatever you use in you app] 

作爲替代解決方案,你可以嘗試迫使Web瀏覽器忽略同源策略(期間只開發/測試!)(例如:--disable-web-security Chrome瀏覽器) - 但這是危險的,如果你這樣做不要注意使用單獨的Web瀏覽器實例進行測試,並且需要定期瀏覽網頁。

+0

嘿,謝謝你的回答。我會檢查這個,看看它是否有幫助 –