Skip to content

Instantly share code, notes, and snippets.

@lduboeuf
Last active February 8, 2017 08:19
Show Gist options
  • Save lduboeuf/6a9ab59dfc0cf85798439af7acd4309b to your computer and use it in GitHub Desktop.
Save lduboeuf/6a9ab59dfc0cf85798439af7acd4309b to your computer and use it in GitHub Desktop.
client java - parse WS json rest
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.lduboeuf.todo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.lduboeuf.todo.model.Task;
/**
*
* @author lionel
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/api/v1/todos");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int httpStatus = conn.getResponseCode();
if (httpStatus!=200){
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "something wrong with server?:{0}", conn.getResponseMessage());
}
String response = streamToString(conn.getInputStream());
Logger.getLogger(Main.class.getName()).log(Level.INFO, "raw response:" + response);
conn.disconnect();
List<Task> tasks = parseTasks(response);
for (Task t: tasks){
Logger.getLogger(Main.class.getName()).log(Level.INFO, t.getTask());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static List<Task> parseTasks(String str){
JSONArray new_array = new JSONArray(str);
List<Task> tasks = new ArrayList<>();
for (int i = 0, count = new_array.length(); i < count; i++) {
JSONObject jsonObject = new_array.getJSONObject(i);
int id = jsonObject.getInt("id");
String task = jsonObject.getString("task");
int status = jsonObject.getInt("status");
Task t = new Task(id, task, status);
tasks.add(t);
}
return tasks;
}
private static String streamToString(InputStream is) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment