【问题标题】:Post Request returning error 400 with Java使用 Java 发布请求返回错误 400
【发布时间】:2019-12-13 13:05:07
【问题描述】:

我真的不知道我的 java 代码中的错误在哪里。 我必须使用 REST API 登录 Kofax Total Agility。为此,我尝试使用邮递员来测试我的 json 是否正确构建。这是我的登录 JSON:

{
  "userIdentityWithPassword": {
    "LogOnProtocol": "7",
    "UnconditionalLogOn": false,
    "UserId": "myLogin",
    "Password": "myPassword"
  }
}

我得到了肯定的回答:

{
    "d": {
        "__type": "Session2:http://www.kofax.com/agility/services/sdk",
        "SessionId": "1DE6B79F34054D58AEE1509FE583811F",
        "ResourceId": "873C0F5C8BD34BAFBF4B14FF538FBAEC",
        "DisplayName": "Aurore Mouret",
        "IsValid": true,
        "LogonState": {
            "__type": "LogonState:http://www.kofax.com/agility/services/sdk",
            "FormName": "",
            "LogonStateType": 0
        },
        "ReserveLicenseUsed": false
    }
}

到目前为止,一切都很好。为此我创建了模型:

public class UserIdentityWithPasswordRestRequestModel {
    LogOnWithPassword2RestRequestModel userIdentityWithPassword;
}
public class LogOnWithPassword2RestRequestModel {
    @SerializedName("LogOnProtocol")
    private String logOnProtocol;
    @SerializedName("UnconditionalLogOn")
    private boolean unconditionalLogOn;
    @SerializedName("UserId")
    private String userId; // C640521793431F4486D4EF1586672385
    @SerializedName("Password")
    private String password; // 123456
}

回复:

public class LogOnWithPassword2RestResponseModel {
    private DRestResponseModel d;
}
public class DRestResponseModel {
    @SerializedName("__type")
    private String type;
    @SerializedName("SessionId")
    private String sessionId;
    @SerializedName("ResourceId")
    private String resourceId;
    @SerializedName("DisplayName")
    private String displayName;
    @SerializedName("IsValid")
    private boolean isValid;
    @SerializedName("LogonState")
    private LogonStateRestResponseModel logonState;
    @SerializedName("ReserveLicenseUsed")
    private boolean reserveLicenseUsed;
}
public class LogonStateRestResponseModel {
    @SerializedName("__type")
    private String type;
    @SerializedName("FormName")
    private String formName;
    @SerializedName("LogonStateType")
    private String logonStateType;
}

这些类应该允许我构建 json。 现在我创建了一个构建请求对象并期望响应对象的方法。

public LogOnWithPassword2RestResponseModel logOnWithPassword() throws Exception {
    LogOnWithPassword2RestResponseModel returnValue = new LogOnWithPassword2RestResponseModel();

    // set the HTTP Connection to the KTA Application
    URL url = new URL("http://localhost/TotalAgility/Services/SDK/UserService.svc/json/LogOnWithPassword2");
    HttpURLConnection con = (HttpURLConnection)url.openConnection();

    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json; utf-8");
    con.setDoOutput(true);

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    LogOnWithPassword2RestRequestModel userIdentityWithPassword = new LogOnWithPassword2RestRequestModel();
    // set the values
    userIdentityWithPassword.setLogOnProtocol(logOnProtocol);
    userIdentityWithPassword.setUnconditionalLogOn(unconditionalLogOn);
    userIdentityWithPassword.setUserId(userId);
    userIdentityWithPassword.setPassword(password);

    UserIdentityWithPasswordRestRequestModel userIdentityWithPasswordRestRequestModel =
            new UserIdentityWithPasswordRestRequestModel();
    userIdentityWithPasswordRestRequestModel.setUserIdentityWithPassword(userIdentityWithPassword);

    // Convert to Json :
    String jsonInputString = gson.toJson(userIdentityWithPasswordRestRequestModel);
    System.out.println(jsonInputString);

    // add request parameter, form parameters
    try(OutputStream os = con.getOutputStream()) {
        byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
        os.write(input, 0, input.length);
        System.out.println("OS " + os);
    }

    // get the response from KTA
    try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
        StringBuilder response = new StringBuilder();
        String responseLine = null;
        while ((responseLine = br.readLine()) != null) {
            response.append(responseLine.trim());
        }
        System.out.println(response.toString());
        returnValue = gson.fromJson(response.toString(), LogOnWithPassword2RestResponseModel.class);
        System.out.println(returnValue);
    }

    return returnValue;
}

当我调用这部分代码时,我注意到我构建了“正确”的 JSON:

{
  "userIdentityWithPassword": {
    "LogOnProtocol": "7",
    "UnconditionalLogOn": false,
    "UserId": "myLogin",
    "Password": "myPassword"
  }
}

由于我无法解释的原因,我收到错误 400。

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: http://94.247.28.163/TotalAgility/Services/SDK/UserService.svc/json/LogOnWithPassword2
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1913)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
    at com.signature.app.ui.controller.DocumentController.logOnWithPassword(DocumentController.java:71)
    at com.signature.app.Main.main(Main.java:21)

第71行对应try catch的这一行

try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)))

【问题讨论】:

  • 我不是 Java 专家,但我认为您可能在 REST 请求中缺少一些标头,例如 Content-Type:'application/json'。
  • 我在这里添加内容类型:con.setRequestProperty("Content-Type", "application/json; utf-8");
  • 在 POSTMAN 上能成功运行吗?
  • 是的!我终于解决了

标签: java rest kofax


【解决方案1】:

我换了

con.setRequestProperty("Content-Type", "application/json; utf-8");

使用此代码:

con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2020-11-19
    相关资源
    最近更新 更多