chohyunwook chohyunwook - 3 months ago 14
JSON Question

How to JSON parser from web page on android?

I don't know how to use JSON parser from web

first, In my website only text

{"name":"hellohello", "age":"19","address":"123123123","phone":"00000"}


and I know use
JSON parser
on android

TextView textmessage;
String mStrJson;
public void onParser() {
String strData ="";
try {
JSONArray json = new JSONArray(mStr);
for(int i=0; i < json.length(); i++) {
JSONObject object = json.getJSONObject(i);
strData += object.getString("name") + " - " + "\n" + object.getInt("age") + "\n";
}
} catch (JSONException e) {
Log.d("tag", "parse error");
}
textmessage.setText(strData);
}


but I don't know how to get web page text?

please advice for me thanks.

Answer

Use this method.

public String getJSONFromUrl(String url) {
        HttpURLConnection c = null;
        try {
            URL u = new URL(url);
            c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setRequestProperty("Content-length", "0");
            c.setUseCaches(false);
            c.setAllowUserInteraction(false);
            c.setConnectTimeout(5000);
            c.setReadTimeout(5000);
            c.connect();
            int status = c.getResponseCode();
            switch (status) {
                case 200:
                case 201:
                    BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line).append("\n");
                    }
                    br.close();
                    return sb.toString();
            }
        } catch (IOException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (c != null) {
                try {
                    c.disconnect();
                } catch (Exception ex) {
                    Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return null;
    }
Comments