lost Coder
lost Coder

Reputation: 577

Making a call similar to ajax using java

I have went through this Previous post on how to do an ajax equivalent call using in java.How to retrieve the response if the request is returning a 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();`

Upvotes: 0

Views: 1000

Answers (2)

Ravindra Thorat
Ravindra Thorat

Reputation: 2002

Try to process getInputStream() method of HttpURLConnection object. It will give you response from the target URI.

Try this,

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;
    }

Upvotes: 1

Pouriya Zarbafian
Pouriya Zarbafian

Reputation: 528

Try this:

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

Upvotes: 1

Related Questions