使用java进行类似于ajax的调用

时间:2015-06-05 09:05:56

标签: java

我已经通过这个SubmitDisabledControls了解如何在java.How中使用ajax等效调用来检索请求返回json时的响应。

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

2 个答案:

答案 0 :(得分:1)

试试这个:

StringBuffer jsonBuffer = new StringBuffer();
BufferedReader reader = null;
String line = null;
try {
    reader =  new BufferedReader(new InputStreamReader(inputStream));
    while ((line = reader.readLine()) != null)
        jsonBuffer.append(line);
} catch (Exception e) {
    //Handle error
}
finally {
    reader.close();
}
String json = jsonBuffer.toString();

答案 1 :(得分:1)

尝试处理getInputStream()对象的HttpURLConnection方法。它将为您提供目标URI的响应。

试试这个,

public JSONObject getResult() {

        String uri = "http://example.com"

        JSONObject jsonResponse = null;
        try {
            URL url = new URL(uri);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/json");

            if (conn.getResponseCode() != HttpURLConnection.OK) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

             String jsonResponseString = br.readLine();

            /**
             * jsonResponse will be having data from target, convert it to JSONObject
             */
            jsonResponse = new JSONObject(jsonResponseString);

            conn.disconnect();

        } catch (MalformedURLException e) {

        } catch (IOException e) {

        } catch (JSONException ex) {

        }
        return jsonResponse;
    }