Java:无法在捕获中发送HTTP发布请求

时间:2019-10-22 07:59:22

标签: java http try-catch com.sun.net.httpserver

我需要将请求发布到catch中的API以存储一些日志。 但是,当我将请求放入catch时,它返回了: java.io.IOException: Server returned HTTP response code: 500 for URL

代码:

try {
    ...
} catch (Exception e) {
    postRequest(...);
}

对API的代码发布请求;

public static Object postRequest(...) throws IOException, ParseException {

    URL url = new URL(API + "/" + pathName);
    HttpURLConnection connection = getHttpURLConnection(url);

    try (OutputStream os = connection.getOutputStream()) {
        byte[] input = body.getBytes("utf-8");
        os.write(input, 0, input.length);
    }

    try {
        StringBuilder response = new StringBuilder();
        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), "utf-8");
        BufferedReader br = new BufferedReader(inputStreamReader);
        String responseLine = null;
        while ((responseLine = br.readLine()) != null) {
            response.append(responseLine.trim());
        }


        JSONParser parser = new JSONParser();
        JSONObject obj = (JSONObject) parser.parse(response.toString());

        return obj;

    } catch (IOException err) {
        return null;
    }
}

0 个答案:

没有答案