我正在努力与其他一些API集成,我需要调用他们的URL来接收数据。
我只是想知道是否可以使用REST Web服务,该服务将映射到某个URL而不是本地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();
}
}
我无法从客户端进行直接API调用,例如使用AngularJs,因为我收到此错误:
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.
我确实找到了来自java的对URL的直接API调用的代码示例,但它看起来很混乱,尤其是当您必须为大量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 :(得分:0)
您正面临同一来源政策问题。
这是因为您的客户端(Web浏览器)应用程序是从Server-A获取的,同时它尝试与Server-B上的数据进行交互。
出于安全原因,默认情况下,只有源自Server-B的代码可以与通信到服务器B(过度简化一点点)。这是为了防止来自Server-A的恶意代码劫持来自Server-B的合法应用程序,并诱使它在用户的后面操纵Server-B上的数据。
要解决此问题,如果Server-A的合法应用程序需要与Server-B通信,则Server-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浏览器忽略相同的源策略(例如:Chrome的--disable-web-security
) - 但这是如果您不注意为测试使用单独的Web浏览器实例以及常规Web浏览,则会产生危险。