简体   繁体   中英

AJAX call in Java Controller without jquery

I'm using following code to make a AJAX call using jQuery.

$.ajax({
    url : "http://localhost:8080/v1/student?studentId=a3a802fcc7604a46a49d5c57150d8d99",
    type : "GET",
    crossDomain : true,
    timeout : 50000,
    success : function(response) {
        console.log("SUCCESS: ", response);
        loadSidebar(response);              
    },
    error : function(xhr, status, error) {
        console.log("ERROR: ", error);
    }
}); 

I would like to make this call using Java in my Controller instead of using jquery and get the JSON response in my response variable.

Can anyone help me out to convert the above code to JAVA code?

I achieved it in my Java Controller as follows:

try {
    URL url = new URL("http://localhost:8080/v1/student?studentId=a3a802fcc7604a46a49d5c57150d8d99");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("Accept", "application/json");
    con.setConnectTimeout(50000);

    if (con.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + con.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
    String output = br.readLine();
    System.out.println(output);

    con.disconnect();

} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM