Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

http json reader #79

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions util/HttpJSONReader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package org.json.util;

/************************************************************************************************
* *
* This class contains static methods for reading and parsing http json response *
* *
* *
* *
* Copyright Gamal Shaban 2012. *
* gemy21ce@gmail.com *
* *
* *
* *
* *
************************************************************************************************/

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;

/**
* This provides reading json from http response,parse it into json object.
*
* @author Gamal Shaban
*/
public final class HttpJSONReader {

/**
* read from the Reader object.
*
* @param rd
* @return
* @throws IOException
*/
protected static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}

/**
* read the url and passes the response as String.
*
* @param url
* @return
*/
public static String readOnly(String url) throws MalformedURLException, IOException {

InputStream is = new URL(url).openStream();
//surround the statments with try and finally so make sure that inputstream will be closed.
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
return jsonText;
} finally {
is.close();
}


}

/**
* reads the url and passes the response as json object.
*
* @param url
* @return
*/
public static JSONObject readAndParse(String url) throws JSONException, MalformedURLException, IOException {
//call the readOnly method and parse the json.
JSONObject json = new JSONObject(readOnly(url));
return json;
}

/**
* parse a json string and returns the json object representation.
*
* @param jsonString
* @return
*/
public static JSONObject parse(String jsonString) throws JSONException {
return new JSONObject(jsonString);
}
}