Ajax call in Java client application

Possible duplicate:
How to use servlets and Ajax?

I use the following code in Javascript to call Ajax:

function getPersonDataFromServer() { $.ajax({ type: "POST", timeout: 30000, url: "SearchPerson.aspx/PersonSearch", data: "{ 'fNamn' : '" + stringData + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { ... } }); } 

I would like to do this in Java too. Basically, I would like to write a Java client application that sends this data through Ajax calls to the server.

How to make Ajax in Java?

+7
source share
1 answer

AJAX is no different than any other HTTP call. Basically, you can send the same URL from Java, and that doesn't matter for the destination server:

 final URL url = new URL("http://localhost:8080/SearchPerson.aspx/PersonSearch"); final URLConnection urlConnection = url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); urlConnection.connect(); final OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(("{\"fNamn\": \"" + stringData + "\"}").getBytes("UTF-8")); outputStream.flush(); final InputStream inputStream = urlConnection.getInputStream(); 

The above code is more or less equivalent to your jQuery AJAX call. Of course, you should replace localhost:8080 with the actual server name.

If you need a more comprehensive solution, consider and to sort JSON.

see also

+8
source

All Articles