首页 文章

jhipster不使用POST REST API

提问于
浏览
0

我想将值POST到JHIPSTER中的实体

我在我的实体名称Hussain中有一个名为name的字段,类型为Long

我写这个代码但它给了我一个错误401,如果只发布一个名称,如果我添加id与它我得到400错误

private void sendPost(long n) throws Exception {
    String url = "http://localhost:8080/api/hussains";

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            //add request header
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept", "application/json");
            con.setRequestProperty("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTUzNDA4Nzg4OX0.AbI_AmN8ePTZ2blULuAKlls-YUPYMD9EHBqIgk_fbktdzJH7hhkEYhQw7settlM04n5N2MHRtGzC1b4z_PDw-Q");

            // optional default is POST
            con.setRequestMethod("POST");

             //Create JSONObject here
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("name", 10);
            OutputStreamWriter out = new   OutputStreamWriter(con.getOutputStream());
            out.write(jsonParam.toString());
            out.close();  



            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            System.out.println(response.toString());

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);


        }

我收到了这个错误

java.io.IOException: Server returned HTTP response code: 401 for URL: http://localhost:8080/api/hussains
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
        at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)

1 回答

  • 1

    首先,您不必使用POST方法发送id,因为id将由您的后端创建 .

    您获得的401是未经授权的,因此您必须查明您的请求是否经过身份验证和未经授权 .

    由于错误请求,您获得400 .

相关问题