http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
(org.json-20120521.jar)
String result = "";
String url1 = "http://localhost:8080/getDVDList";
URL url = new URL(url1);
URL obj = url;
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
result = response.toString();
// Parse to get translated text
JSONObject jsonObject = new JSONObject(result);
JSONArray dvdList = jsonObject.getJSONArray("body");
List<Dvd> list = null;
if(dvdList != null){
list = new ArrayList<>();
for(int i = 0; i < dvdList.length(); i++){
JSONObject c = dvdList.getJSONObject(i);
Dvd d = new Dvd(c.getInt("code"), c.getString("title"), c.getString("actors"), c.getInt("rating"),c.getString("definiiton"), c.getString("year"));
list.add(d);
}
}
2.)
JSONObject jsonObject = new JSONObject(result);
int code = jsonObject.getJSONObject("responseCode").getInt("code");
if (code == 201) {
errorLabel.setForeground(Color.BLACK);
errorLabel.setText("DVD Successfully Added.");
} else {
errorLabel.setForeground(Color.RED);
errorLabel.setText("Adding DVD failed");
}
3.) String url1 = "http://localhost:8080/addDVD?title=" + URLEncoder.encode(title, "UTF-8").replace("+", "%20") + "&year=" + year + "&actors=" + URLEncoder.encode(actors, "UTF-8").replace("+", "%20") + "&ratings=" + ratings + "&definitions=" + definitions;
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("Content-Language", "en-US");
// optional default is GET
con.setRequestMethod("POST");
URLDecoder.decode (title);
No comments:
Post a Comment