通过java发送post请求时出现http 400错误

xam8gpfp  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(436)

当我试图发送post请求时,我得到了一个400错误,但是,当我查看代码时,我的正文格式是正确的,所以我不确定为什么会得到错误。下面是我的代码:

public class Endpoint {

    public void endpointtest() {
        StringBuilder response = new StringBuilder();

        Gson g = new Gson();
        JsonParser jsonParser = new JsonParser();

        String urll = "http://localhost:8085/endpoint";
        try {

            //creating the connection
            URL url = new URL(urll);

            HttpClient client = HttpClient.newHttpClient();

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);

            connection.setRequestMethod("POST");
            connection.setConnectTimeout(150000);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();

            String json =  "{\"user\":\"c86de524\",\"pass\":22923947}";

            //builds the post body, adds parameters
         DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(g.toJson(json));
            out.flush();
            out.close();

            //Reading the response
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputline;
            while ((inputline = in.readLine()) != null) {
                response.append(inputline);
            }
            in.close();

            System.out.println(response.toString());

            //status of connection
            connection.getResponseCode();
            connection.disconnect();

            System.out.println(response.toString());

        } catch (final Exception ex) {

            ex.printStackTrace();
            System.out.println("something went wrong ");

        }

当我调用这个类中的方法时,我得到了400错误。我不明白,因为我有我的json字符串,我转换成json使用gson库,所以我会发送我的请求与正确的格式。为什么会发生这种错误?下面是stacktrace:

java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8080/endpoint
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 Endpoint.endpointtest(Endpoint.java:51)
at main.main(Endpoint.java:81)

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题