当前位置: 首页 > 知识库问答 >
问题:

发布请求返回错误400与Java

毛正浩
2023-03-14

我真的不知道我的java代码中的错误在哪里。我必须使用REST API登录Kofax Total Agility。为此,我尝试使用postman测试我的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(buffered reader br = new buffered reader(new InputStreamReader(con . getinputstream(),StandardCharsets。UTF_8)))

共有1个答案

戚正业
2023-03-14

我更换了

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

使用此代码:

con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
 类似资料:
  • 问题内容: 这工作正常: 这将返回400 Bad Request(只是使用.ajax来支持错误处理的上述jQuery的重新格式)。 问题答案: 我认为您只需要再添加2个选项(和):

  • 我试图使用Gmail API将用户设置应用到Gmail帐户,但它不断返回错误400错误请求。 我可以看到错误代码在Gmail API控制台,它来自我的服务号,所以代码不可能是如此错误,但它让我发疯,只是不能找出什么是错误的。 如果有人能给我指出正确的方向,我会非常感激。

  • 我试图对我写的rest api执行一个put请求,但它总是返回400-bug请求。 java.io.IO异常:服务器返回HTTP响应代码:400为URL:http://localhost:8000/api/v0/contacts/2sun.net.www.protocol.http.HttpURLConnection.getInputStream(未知来源) 我可以用firefox rest客户端

  • 问题内容: 我有这个应用程序,它可以在本地运行,并且在部署时可以使用.mdf SQL Express数据库文件(通常用于测试目的)。但是,当我将其更改为可与我们的SQL Server 2008一起使用时,该应用程序可以运行,但该服务无法运行。 例如,如果在页面后面的代码中,我有一个按钮可以向表中添加数据,例如: 我的web.config设置为在该服务器上使用模拟,并且一切运行良好。但是,对于我的服

  • 当我添加ACDailyLine时,两个post方法的请求都变为4oo错误 为什么当我只放ACDailyH post方法时,一切正常,返回201请求。当我为AcDailyLine添加时,两者都返回400个错误请求。请帮忙,提前谢谢:) 在这里,当我调试该行时

  • 我在Tomcat中部署了一个Java的Web应用程序。 如果我的URL是这样的,我会收到来自Tomcat 8的400个错误请求 编码为 但是如果我从 URL 中删除 a:b:ab,a:b:abc 和 renditionFilter=cmis:thumbnail,application/pdf,image/bmp,image/gif,image/jpeg,image/png,那么它就可以工作了,这个