8

重複の可能性:
サーブレットとAjaxの使用方法は?

私はJavascriptで次のコードを使用してAjax呼び出しを行います。

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クライアントアプリケーションを作成したいと思います。

JavaでAjaxを実行するにはどうすればよいですか?

4

1 に答える 1

9

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

See also

于 2012-10-07T12:26:53.130 に答える