解决 Rest API 调用状态码 400 问题

其实我知道这是因为请求不好。但我无法弄清楚问题所在。我创建了一个 java 类来调用一个接受 JSON 对象并返回 A JSON 作为响应的 REST API。以下是我的 JAVA 代码


public static void dataTest() {

    List<String> resultSet = new ArrayList<>();

    try {

        URL url = new URL("http://localhost:8080/login/");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setDoOutput(true);

        conn.setRequestMethod("POST");

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

        String input = "{\"mobile_number\":0719402232,\"pin\":\"1111\"}";

        OutputStream os = conn.getOutputStream();

        os.write(input.getBytes());

        os.flush();


        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {

            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());

        }


        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));


        String output;

        System.out.println("Output from Server .... \n");


        while ((output = br.readLine()) != null) {

            resultSet.add(output);

            System.out.println(output);

        }

        conn.disconnect();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

但我收到 400 状态码。


而且我还需要将返回的 JSON 传递给 JSP。以下是我访问 JAVA 类的方式


  <ul>

        <c:forEach items="${AddOrigin.DataTest()}" var="ListItem">

            <li>${ListItem.name}</li>

        </c:forEach>

  </ul>

在 JSP 中查看以下错误


org.apache.jasper.JasperException: An exception occurred processing [/dwpages/AddOrigin.jsp] at line [359]


356:                            <div id="main-content"></div>

357: 

358:                            <ul>

359:                                <c:forEach items="${AddOrigin.DataTest()}" var="ListItem">

360:                                    <li>${ListItem.name}</li>

361:                                </c:forEach>

362:            

慕田峪4524236
浏览 823回答 2
2回答

DIEA

我认为您应该将电话号码作为字符串传递(在引号之间)

临摹微笑

我的java代码我有以下行String&nbsp;input&nbsp;=&nbsp;"{\"mobile_number\":0719402232,\"pin\":\"1111\"}";它必须改为String&nbsp;input&nbsp;=&nbsp;"{\"mobile_number\":\"0719402232\",\"pin\":\"1111\"}";
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java