在Java客户端应用程序Ajax调用 [英] Ajax call in Java client application

查看:152
本文介绍了在Java客户端应用程序Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  如何使用servlet和阿贾克斯?

我使用下面的code在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中也是如此。基本上,我想编写一个发送通过Ajax这些数据需要到服务器的Java客户端应用程序。

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中做阿贾克斯?

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

在code以上或多或少相当于你的jQuery AJAX调用。当然,你必须更换本地主机: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.

如果你需要更多的COM prehensive的解决方案,可以考虑库和以JSON编组

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

这篇关于在Java客户端应用程序Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆