8

Possible Duplicate:
How to use Servlets and Ajax?

I am using the following code in Javascript to makes an Ajax call:

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 as well. Basically, I would like to write a Java client application which send this data via Ajax calls to the server.

How do I do Ajax in Java?

Community
  • 1
  • 1
amyr sos
  • 83
  • 1
  • 1
  • 5

1 Answers1

9

AJAX is no different from any other HTTP call. You can basically POST the same URL from Java and it shouldn't matter as far as the target server is concerned:

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 code above is more or less equivalent to your jQuery AJAX call. Of course you have to replace localhost:8080 with the actual server name.

If you need more comprehensive solution, consider library and for JSON marshalling.

See also

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • Thank you Tomasz for your reply. But still, I have a question! I would like to send the request to http://www.ratsit.se/BC/SearchPerson.aspx website. I have read their client part code and understood that they are sending in the following way: http://codepaste.net/u7qc1o Now I would like to write this ajax request in Java I did the things that you mentioned in the answer: http://codepaste.net/1rbgpx but still nothing,,, Can you help me please and let me know what is wrong ? – amyr sos Oct 07 '12 at 15:38