ViewVC Help
View File | Revision Log | View Changeset | Root Listing
root/Oni2/AE/installer2/src/net/oni2/aeinstaller/backend/network/DrupalJSONQuery.java
Revision: 633
Committed: Fri Jan 18 18:18:45 2013 UTC (12 years, 8 months ago) by alloc
Content type: text/x-java
File size: 2275 byte(s)
Log Message:
AEI2 0.92a:
- Updated depot-sync to use serverside caches

File Contents

# Content
1 package net.oni2.aeinstaller.backend.network;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.io.UnsupportedEncodingException;
7
8 import org.apache.http.HttpEntity;
9 import org.apache.http.HttpResponse;
10 import org.apache.http.client.methods.HttpGet;
11 import org.apache.http.client.methods.HttpRequestBase;
12 import org.apache.http.impl.client.DefaultHttpClient;
13 import org.apache.http.util.EntityUtils;
14 import org.json.JSONArray;
15 import org.json.JSONException;
16 import org.json.JSONObject;
17
18 /**
19 * @author Christian Illy
20 */
21 public class DrupalJSONQuery {
22
23 /**
24 * Get the JSON array found at the given url
25 *
26 * @param url
27 * URL to look at for the JSON data
28 * @return JSON array of data
29 * @throws Exception
30 * On HTTP status code <200 / >299
31 */
32 public static JSONArray executeQuery(String url) throws Exception {
33 BufferedReader input = null;
34 HttpRequestBase httpQuery = null;
35
36 try {
37 DefaultHttpClient httpclient = new DefaultHttpClient();
38 httpQuery = new HttpGet(url);
39
40 HttpResponse response = httpclient.execute(httpQuery);
41
42 int code = response.getStatusLine().getStatusCode();
43 if ((code > 299) || (code < 200)) {
44 throw new Exception(String.format(
45 "Error fetching content (HTTP status code %d).", code));
46 }
47
48 HttpEntity entity = response.getEntity();
49
50 input = new BufferedReader(new InputStreamReader(
51 entity.getContent()));
52 StringBuffer json = new StringBuffer();
53
54 char data[] = new char[1024];
55 int dataRead;
56 while ((dataRead = input.read(data, 0, 1024)) != -1) {
57 json.append(data, 0, dataRead);
58 }
59
60 EntityUtils.consume(entity);
61
62 JSONArray jA = null;
63 if (json.charAt(0) == '{') {
64 jA = new JSONArray();
65 jA.put(new JSONObject(json.toString()));
66 } else
67 jA = new JSONArray(json.toString());
68
69 return jA;
70 } catch (JSONException e) {
71 e.printStackTrace();
72 } catch (UnsupportedEncodingException e) {
73 e.printStackTrace();
74 } catch (IOException e) {
75 e.printStackTrace();
76 } finally {
77 if (httpQuery != null)
78 httpQuery.releaseConnection();
79 if (input != null) {
80 try {
81 input.close();
82 } catch (IOException e) {
83 e.printStackTrace();
84 }
85 }
86 }
87 return null;
88 }
89 }