【问题标题】:How to emulate curl --data 'some_content=xyz' on Play Framework?如何在 Play Framework 上模拟 curl --data 'some_content=xyz'?
【发布时间】:2016-02-22 08:04:21
【问题描述】:

我一直在测试一些外部 API,这个 curl 命令可以完美地与 API 的端点交互:

curl -i -L -H 'Accept: application/json' --data 'client_id=11111111&client_secret=2222222222' 'https://some.api.com/endpoint'

但是,我无法在 Play Framework 上模拟同样的调用。无论我尝试什么,外部 API 仍然返回一个错误,说“client_id 为空”。当我使用 curl 命令时不会出现此错误,因此我必须得出结论,我使用 Play Framework 执行此操作的方式存在问题。

这是我迄今为止尝试过的:

// Using the parameters directly in the endpoint

String data = "client_id=" + MY_CLIENT_ID;
data += "&client_secret=" + MY_CLIENT_SECRET;

WSRequestHolder request = WS.url("https://some.api.com/endpoint/" + data);
request.setHeader("Accept", "application/json");

Promise<Result> promise = request.post("").map(new Function<WS.Response, Result>() { ... }

不同的测试:

// Using the data input as JSON

ObjectNode node = Json.newObject();
node.put("client_id", MY_CLIENT_ID);
node.put("client_secret", MY_CLIENT_SECRET);

WSRequestHolder request = WS.url("https://some.api.com/endpoint/");
request.setHeader("Accept", "application/json");

Promise<Result> promise = request.post(node).map(new Function<WS.Response, Result>() {...}

我也尝试将数据字符串和 JSON 节点转换为 InputStream:

ByteArrayInputStream input = new ByteArrayInputStream(node.toString().getBytes());

然后这样使用它:

Promise<Result> promise = request.post(input).map(new Function<WS.Response, Result>() {...}

结果总是“client_id is empty”错误。

我正在使用 Play 2.1.5(使用 Java)。

感谢您提供的任何帮助。

【问题讨论】:

    标签: java web-services curl playframework


    【解决方案1】:

    你几乎明白了。 试试

    WS.url("http://localhost:9000/echo").
                setFollowRedirects(true).
                setHeader("Accept", "application/json").
                setHeader("Content-Type", "application/x-www-form-urlencoded").
              post("client_id=11111111&client_secret=2222222222");
    
    • curl -L -> setFollowRedirect(true) 不确定 -i 是否会像 curl 一样工作
    • curl --data -> 添加内容类型标题

    【讨论】:

    • 太棒了!就是这样。谢谢,伙计。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2017-10-10
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多