Reputation: 127
I want to POST value to an entity in JHIPSTER
I have in my entity name Hussain with one field called name with a type Long
I write this code but it gives me an error 401 if only post a name and if I add id with it I got 400 error
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); }
and i got this error
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)
Upvotes: 0
Views: 864
Reputation: 15908
First of all, you don't have to send id with POST method because id will be created by your back-end.
You get 401 which is unauthorized so you have to find out whether your request is authenticated and unauthorized or not.
You get 400 because of Bad Request.
Upvotes: 1