【发布时间】:2023-03-07 13:34:01
【问题描述】:
我正在与一些其他 API 集成,我需要调用他们的 URL 来接收数据。
我只是想知道是否可以使用将映射到特定 URL 而不是本地 URL 的 REST Web 服务,稍后我将编写将映射到这些调用的客户端。
例如:
@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 对 URLS 的直接 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();
}
}
}
【问题讨论】: