I'm trying to make a http get request which returns a json response. I need some of the values from the json response to be stored in my session. I have this:
public String getSessionKey(){
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
try {
URL url = new URL(//url here);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null)
{
sb.append(line + '\n');
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
This returns the JSON in a string:
{ "StatusCode": 0, "StatusInfo": "Processed and Logged OK", "CustomerName": "Mr API"}
I need to store StatusCode and CustomerName in the session. How do I deal with returning JSON with java?
Thanks
You can use Gson. Here is the code to help you:
Map<String, Object> jsonMap;
Gson gson = new Gson();
Type outputType = new TypeToken<Map<String, Object>>(){}.getType();
jsonMap = gson.fromJson("here your string", outputType);
Now you know how to get from and put those in session. You need to include Gson library in classpath.
Use a JSON library. This is an example with Jackson:
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(connection.getInputStream());
// Grab statusCode with node.get("StatusCode").intValue()
// Grab CustomerName with node.get("CustomerName").textValue()
Note that this will not check the validity of the returned JSON. For this, you can use JSON Schema. There are Java implementations available.
For session storage you can use an Aplication context class: Application, or use a static global variable.
For parsing JSON from HttpURLConnection you can use a method such as this:
public JSONArray getJSONFromUrl(String url) {
JSONArray jsonArray = null;
try {
URL u = new URL(url);
httpURLConnection = (HttpURLConnection) u.openConnection();
httpURLConnection.setRequestMethod("GET");
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + '\n');
}
jsonString = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpURLConnection.disconnect();
}
try {
jsonArray = new JSONArray(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonArray;
}
Check out the GSON library for converting json into objects and vice versa.
http://code.google.com/p/google-gson/
You could try this:
JSONObject json = new JSONObject(new JSONTokener(sb.toString()));
json.getInt("StatusCode");
json.getString("CustomerName");
And do not forget to wrap it into try-catch
My method with the parameters in the call to use the Service or AsyncTask
public JSONArray getJSONFromUrl(String endpoint, Map<String, String> params)
throws IOException
{
JSONArray jsonArray = null;
String jsonString = null;
HttpURLConnection conn = null;
String line;
URL url;
try
{
url = new URL(endpoint);
}
catch (MalformedURLException e)
{
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext())
{
Map.Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
byte[] bytes = body.getBytes();
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line + '\n');
}
jsonString = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
try {
jsonArray = new JSONArray(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonArray;
}