2016-12-06 127 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

嘿,谢谢你的回答。我会检查这个,看看它是否有帮助 –