Get網絡請求解析json串



// /得到HttpClient對象
  HttpClient httpClient = new DefaultHttpClient();
  // 得到連接方式對象,設置請求路徑
  HttpGet httpGet = new HttpGet(path);

  try {
   // GET方式請求接口,得到響應內容
   HttpResponse httpResponse = httpClient.execute(httpGet);

   // 得到狀態行
   StatusLine statusLine = httpResponse.getStatusLine();
   // 得到狀態碼
   int statusCode = statusLine.getStatusCode();
   // 如果狀態碼等於200,代表請求成功
   if (statusCode == 200) {
    // 得到包含着數據的實體
    HttpEntity entity = httpResponse.getEntity();
    // 講實體轉換成String,並設置編碼集
    String data = EntityUtils.toString(entity, "UTF-8");
    // System.out.println(data);
    // 解析json
    Gson gson = new Gson();
    Bean bean = gson.fromJson(data, Bean.class);
    Message msg = Message.obtain();
    msg.obj = bean;
    handler.sendMessage(msg);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章