Java脚本java.io. io异常:服务器返回HTTP响应代码400

bxjv4tth  于 2023-03-11  发布在  Java
关注(0)|答案(1)|浏览(262)

我正在使用以下代码调用Rest API,以便在目标应用程序中创建User,但如果我在Postman中发布重复的用户信息,则会收到“400 Bad Request”,其中以下数据为JSON。

{
    "errorCode": "E0000001",
    "errorSummary": "Api validation failed: login",
    "errorLink": "E0000001",
    "errorId": "xxxxxxxxxxxxxxxxxxxxxxxxx",
    "errorCauses": [
        {
            "errorSummary": "login: An object with this field already exists in the current organization"
        }
    ]
}

我正在使用下面的代码来获得响应,当我得到“400坏请求”时无法获得响应。
剩余呼叫详细信息:https://developer.okta.com/docs/reference/api/users/#create-user-with-password
在API调用中,我将Authorization令牌发布到消息头SSWS xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxx
我在正文中发布以下数据。

{
    "profile": {
        "firstName": "John1",
        "lastName": "Flow1",
        "email": "john1.flow1@test.com",
        "login": "john1.flow1@test.com",
        "mobilePhone": ""
    },
    "credentials": {
        "password": {
            "value": "xxxxxxxx"
        }
    }
}

java.io.IOException:服务器返回HTTP响应代码:400用于URL:https://test-app.testlab.com/api/v1/users"

function CreateUserInApp(rest_url, api_token, postJSON) {
    try {
        var postValBytes = new java.lang.String(postJSON).getBytes("UTF8");
        var posturl = new java.net.URL(rest_url);
        var stream = posturl.openConnection();
        stream.setRequestMethod("POST");
        stream.setRequestProperty("Accept", "application/json");
        stream.setRequestProperty("Content-Type", "application/json");
        stream.setRequestProperty("Authorization", api_token);
        stream.setDoOutput(true);
        stream.setDoInput(true);
        var outStream = stream.getOutputStream();
        outStream["write(byte[])"](postValBytes);
        outStream.flush();
        var responseCode = stream.getResponseCode();
        var stream = new java.io.BufferedReader(new java.io.InputStreamReader(stream.getInputStream()));
        var inputLine;
        var response = new java.lang.StringBuilder();
        while ((inputLine = stream.readLine()) != null) {
            response.append(inputLine);
        }
        var response = response.toString();
        return response;
    } catch(e) {
        return "ERROR Is: " + e.toString();
    }
}

我不确定我是否正确关闭了连接,请帮助我解决这个问题。

holgip5t

holgip5t1#

我已经使用getErrorStream()解决了这个问题,我更新了下面的代码。

var stream_in = "";
if(responseCode == "200") {
    stream_in = new java.io.BufferedReader(new java.io.InputStreamReader(stream.getInputStream()));
} else {
    stream_in = new java.io.BufferedReader(new java.io.InputStreamReader(stream.getErrorStream()));
}

请建议如果我错过了什么或什么,我可以改进这一点。

相关问题