从java客户端发布到Django表单vs curl -d



我在这里遇到了一个问题。我正在尝试从Java应用程序向Django API发出请求。我有一个来自命令行的 curl 命令,它就像一个魅力......但是,从Java我无法正确处理。所以。。。卷曲程序:

curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' -d 'username=clientname&password=somepassword' 'https://hostname.domain/api/v1/login'

这让我得到一个响应正文,如下所示:

{
  "success": true,
  "message": "Login OK",
  "token": "iLCJhbGcoOIJIUzI1NiJ9.eyJuYW1lIjoiU0ZMT1JFUy...(truncated)"
}

我的爪哇代码

public Optional<String> login() {
    Form form = new Form();
    form.param("username", USER);
    form.param("password", PASS);
    Entity<Form> requestEntity = Entity.form(form);
    WebTarget target = this.client.target(LOGIN_URL);
    Response response = target.request().accept(MediaType.APPLICATION_JSON).post(requestEntity);
    this.logger.info(String.format("Response status: %s", response));
    if (response.getStatus() == Status.OK.getStatusCode()) {
        LoginResponseDTO loginDTO = response.readEntity(LoginResponseDTO.class);
        return Optional.<String>of(loginDTO.getToken());
    } else {
        this.logger.warn(String.format("%s", response.getStatusInfo()));
        this.logger.warn(String.format("Cannot log user '%s' in", USER));
        return Optional.<String>empty();
    }
}

java代码在调用时会返回BadRequest响应。我已经检查了 Django 日志,POST 的正文似乎是空的,但 java 中的请求携带作为正文传递的形式。如果有人对我错过了什么有一些提示,那就太好了。

提前谢谢。

嗯...原来泽西客户端默认配置压缩了身体...目标 API 不支持该选项。

在应用程序"运行"方法中,我添加了:

    JerseyClientConfiguration clientConfig = new JerseyClientConfiguration();
    clientConfig.setGzipEnabled(false);
    clientConfig.setGzipEnabledForRequests(false);
    Client client = new JerseyClientBuilder(environment).using(clientConfig).build("RESTClient");
    this.petiteBundle.getPetiteContainer().addBean(Client.class.getName(), client);

我花了一段时间才看到这一点,但我能够意识到这是在应用程序的"run"方法中激活请求有效负载转储后发生的:

    environment.jersey().register(
            new LoggingFeature(Logger.getLogger("Main application"), Level.INFO, Verbosity.PAYLOAD_ANY, 100000));

最新更新