首页 > 解决方案 > 我无法捕获异常 400 的服务器响应消息 - Java API

问题描述

我开始通过 API 从我的 java 引擎扫描到 Rapid7 工具。当响应为 400 时,我想从服务器捕获并打印消息。服务器返回 JSON

 {
    "status": 400,
    "message": "An unexpected error occurred. See the log file for more information or contact support.",
    "links": [
        {
            "href": "api/3/sites/3/scans",
            "rel": "self"
        }
    ]
 }

我想将此消息打印到控制台。开始扫描和读取响应工作正常(服务器响应 https 200,201)。问题是服务器响应 400。

读取服务器响应的代码

httpsCode = connection.getResponseCode();

while (true)
                    {
                        //Read
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
// jumps from here to Catch when https code = 400

                        String lines = null;                         StringBuilder stringBuilder = new StringBuilder();
                        while ((lines = bufferedReader.readLine()) != null)
                        {
                            stringBuilder.append(lines);
                        }
                        bufferedReader.close();
                        result = stringBuilder.toString();

                        JSONParser parser = new JSONParser();
                        JSONObject json2 = (JSONObject) parser.parse(result);

                        if(httpsCode ==200 || httpsCode ==201)
                        {
                            if(methodType == MethodType.Add_host_To_Site && method.equals("POST"))
                            {
                                System.out.print("\n Rapid7 : Successful POST, host was added to Rapid7, " + splunkdata.getHost_fqdn() );
                                String asset_id= json2.get("id").toString();
                                splunkdata.getScan().setAsset_Id(Integer.parseInt(asset_id));
                                System.out.print("\n Rapid7 : Asset_id is set successfully , " + splunkdata.getHost_fqdn() );
                            } 
}

 if (httpsCode == 400 || httpsCode == 401)
                        {
                            System.out.print(" Rapid7 : Rapid7 InsightVM throws Exception, \n Message : " + json2.get("message")  );
                        }

 connection.disconnect();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) { // jump to IOException
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();


什么可能导致这个问题?谢谢

标签: javaapi

解决方案


推荐阅读