Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax call in Java client application [duplicate]

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?

like image 337
amyr sos Avatar asked Oct 07 '12 12:10

amyr sos


People also ask

How do I make Ajax calls in Spring MVC?

Code Example – How to Make AJAX Calls with Java Spring MVC. Step 1: Get JQuery Library. Download JQuery library and place it in JS folder within one of your web assets folder. Even simpler, include following ... Step 2: Create a Form. Step 3: Create AJAX Code. Step 4: Create Server-side Code.

How to make an AJAX call using jQuery?

Approach 2: In this approach, we will use jQuery to make an ajax call. The ajax () method is used in jQuery to make ajax calls. It is used as a replacement for all approaches which are not working to make ajax calls. $.ajax ( {arg1: value, arg2: value, ...

What is a Ajax request in Java?

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:

How to create an Ajax example?

To create ajax example, you need to use any server-side language e.g. Servlet, JSP, PHP, ASP.Net etc. Here we are using JSP for generating the server-side code.


1 Answers

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 httpclient library and jackson for JSON marshalling.

See also

  • cURL and HttpURLConnection - Post JSON Data
like image 145
Tomasz Nurkiewicz Avatar answered Sep 19 '22 05:09

Tomasz Nurkiewicz