'Posting JSON to REST API from Java Servlet

I'm having issues trying to send over a JSON string to a REST API. Long story short, I'm taking user input in a form, sending it over to a java servlet to validate and work with it a bit, and then trying to send it to an endpoint.

I have the following method being called on in my doPost method in my servlet, I am using printwriter pw to be able to read back data being returned in my response in the browser console at this point.

String jsonData = //JSON STRING HERE\\
String username = //USERNAME\\
String password = //PASSWORD\\
String endpointURL = //ENDPOINT URL HERE\\

pw.println(sendJson(jsonData, username, password));
private String sendJSON(String jsonData, String usrname, String usrpass) {
    try {
        String auth = usrname + ":" + usrpass;
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
        String authHeaderValue = "Basic " + new String(encodedAuth);
        
    URL url = new URL(endpointURL);
    HttpURLConnection http = (HttpURLConnection)url.openConnection();
    http.setConnectTimeout(5000);
    http.setReadTimeout(5000);
    http.setRequestMethod("POST");
    http.setRequestProperty("Content-Type", "application/json; utf-8");
    http.setRequestProperty("Authorization", authHeaderValue);
    http.setDoOutput(true);
        
    //POST Json to URL using HttpURLConnection
    //try(OutputStream os = http.getOutputStream()) {
        OutputStream os = http.getOutputStream();
        byte[] input = jsonData.getBytes("utf-8");
        os.write(input, 0, input.length);           
    //}
    
    /*String responseBody;
    try(BufferedReader br = new BufferedReader(
              new InputStreamReader(http.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                //System.out.println(response.toString());
                responseBody = response.toString();
                return responseBody;
            }
    
    return responseBody;*/
    
    BufferedReader in = new BufferedReader(
            new InputStreamReader(http.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    
    return response.toString();
    
    } catch (IOException e) {
        return e.toString();
    } 
    
}
}

I was having issues with the try's so I rewrote it to try and just get functionality right away first. Right now I'm receiving "java.io.IOException: Server Returned HTTP response code: 500 for URL: //URL HERE\"

Would anybody have any tips to point me in the right direction? I feel like I'm just missing like a small piece of the puzzle at this point, and I'm having a hard time finding any tutorials showing what it is that I'm trying to do. Thank you so much to anyone for any tips/pointers!

Made sure I was able to authenticate and that wasn't the issue by just connecting and returning:

int statusCode = http.getResponseCode();
String statusCodeString = Integer.toString(statusCode);
return statusCodeString;

This worked fine, received 403 response when setting wrong password/username and 400 response when I change to correct.

I attempted using HttpClient as well instead, but was having issues trying to get that to work at all. I also had an error earlier with week trying to do this with a certificate error, but after reimporting the cert to my cacerts file this was resolved (unrelated to this issue I believe).



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source