Ajax call in Java client application [duplicate]

亡梦爱人 提交于 2019-12-18 16:12:23

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/12768658/ajax-call-in-java-client-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!