Java 客户端应用程序中的 Ajax 调用

2022-01-15 00:00:00 xmlhttprequest ajax httpclient java jackson

可能重复:
如何使用Servlet和Ajax?

我在 Javascript 中使用以下代码进行 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) {
                ...
            }
        });
    }

我也想用 Java 来做这件事.基本上,我想编写一个 Java 客户端应用程序,通过 Ajax 调用将此数据发送到服务器.

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.

如何在 Java 中使用 Ajax?

How do I do Ajax in Java?

推荐答案

AJAX 与任何其他 HTTP 调用没有什么不同.您基本上可以从 Java 发布相同的 URL,就目标服务器而言,这无关紧要:

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();

上面的代码或多或少等同于您的 jQuery AJAX 调用.当然,您必须将 localhost:8080 替换为实际的服务器名称.

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.

如果您需要更全面的解决方案,请考虑 httpclient 库和 jackson 用于 JSON 编组.

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

  • cURL 和 HttpURLConnection - 发布 JSON 数据

相关文章