1. 程式人生 > >android 客戶端訪問自己建立的伺服器並返回JSON資料進行解析學習

android 客戶端訪問自己建立的伺服器並返回JSON資料進行解析學習

最近在找關於客戶端訪問伺服器開發的用例 總是去訪問別人的網站也不能對裡面的資料進行修改也不知道是怎麼實現的,自己在網上申請了一個免費的伺服器網站上傳了一個php檔案,現在就可以通過urlStr===http://1.hellowes.sinaapp.com/訪問伺服器上的資訊了,並且伺服器會返回一個數據,由於對php一點不懂所以伺服器上返回的並不是真正的JSON資料,所以只好通過客戶端字串組合成一個JSON語句通過JSONObject進行解析出來,

下面貼出實現程式碼,總算是可以從伺服器上獲取資訊了

public JSONObject getweb(String urlStr) throws Exception{

StringBuffer sb = new StringBuffer();
  try {
   URL url = new URL(urlStr);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   conn.setConnectTimeout(5000);
   conn.setDoInput(true);
   conn.setDoOutput(true);
   if(conn.getResponseCode() == 200){
    InputStream is = conn.getInputStream();
    int len = 0;
    byte[] buf = new byte[1024];
    while((len = is.read(buf)) != -1){
     sb.append(new String(buf, 0, len, "UTF-8"));
    }
    is.close();
   }else{
    throw new Exception("訪問網路失敗00");
   }

  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   throw new Exception("訪問網路失敗11");
  }
  System.out.println("---------"+sb.toString());
  String htmlStr =  sb.toString();
  htmlStr = htmlStr.replaceAll("\"", "\'");
  htmlStr = "{'singer':"+htmlStr+"}";
  System.out.println("htmlStr===="+htmlStr);
  JSONObject jsonObj = null;
  try {
   jsonObj = new JSONObject(htmlStr).getJSONObject("singer");
   System.out.println("jsonObj===="+jsonObj);
  } catch (JSONException e1) {
   // TODO Auto-generated catch block

   e1.printStackTrace();
  }

return jsonObj;

}