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

來源:互聯網
上載者:User

標籤:伺服器   用戶端   json   php   url   

最近在找關於Client Access Server開發的用例 總是去訪問別人的網站也不能對裡面的資料進行修改也不知道是怎麼實現的,自己在網上申請了一個免費的伺服器網站上傳了一個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;

}

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.