可能重复: 如何使用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("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的解决方案,可以考虑 HttpClient的库和杰克逊以JSON编组
If you need more comprehensive solution, consider httpclient library and jackson for JSON marshalling.
- 卷曲和HttpURLConnection的 - 发布JSON数据
更多推荐
在Java客户端应用程序Ajax调用
发布评论