【问题标题】:RestApi post request to specific URLRest Api 向特定 URL 发布请求
【发布时间】: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();

     }

    }

}

【问题讨论】:

    标签: java rest api post


    【解决方案1】:

    您正面临同源政策问题。

    这是因为您的客户端(Web 浏览器)应用程序是从服务器 A 获取的,同时它尝试与服务器 B 上的数据进行交互。

    • Server-A 是从中获取应用程序的位置(在其在 Web 浏览器上显示给用户之前)。
    • Server-B 是本地主机,你的模拟服务部署到这里

    出于安全原因,默认情况下,只有源自 Server-B 的代码才能对话到 Server-B(有点过于简化了)。这是为了防止来自 Server-A 的恶意代码劫持来自 Server-B 的合法应用程序,并欺骗它在用户背后操纵 Server-B 上的数据。

    为了克服这个问题,如果来自服务器 A 的合法应用程序需要与服务器 B 通信,服务器 B 必须明确允许它。为此,您需要实施 CORS(跨源资源共享) - 尝试使用谷歌搜索,您会发现大量资源可以解释如何做到这一点。 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 浏览器实例进行测试和常规 Web 浏览。

    【讨论】:

    • 您好,谢谢您的回答。我会检查一下,看看它是否有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多