android 擷取http請求json資料,androidjson

來源:互聯網
上載者:User

android 擷取http請求json資料,androidjson

package com.my.gethttpjsondata;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

TextView textView;

static String err;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textView = (TextView) findViewById(R.id.tv_json);

}

public void Click1(View view)
{
//Toast.makeText(MainActivity.this, "開始", 0).show();
//String path="http://192.168.1.151:10080/?module={appId:%22d1%22,id:%22getAllUser%22}";
try {
//textView.setText(getJsonContent(path));
//String r=getJsonContent(path);
//Toast.makeText(MainActivity.this, r, 0).show();
// 開啟一個子線程,進行網路操作,等待有返回結果,使用handler通知UI
new Thread(networkTask).start();

/**
List<Map> list=new ArrayList<Map>();
list=getJSONObject(path,MainActivity.this);
for (Map list2 : list) {
String id = list2.get("UserID").toString();
String name = list2.get("UserName").toString();
Toast.makeText(MainActivity.this, "id:" + id + " | name:" + name, 0).show();
}
**/

} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), 0).show();
e.printStackTrace();
}

}

/**
* 網路操作相關的子線程
*/
Runnable networkTask = new Runnable() {

@Override
public void run() {
String path="http://192.168.1.151:10080/?module={appId:%22d1%22,id:%22getAllUser%22}";
List<Map> list=new ArrayList<Map>();
try {
list=getJSONObject(path);
} catch (Exception e) {

e.printStackTrace();
}
for (Map list2 : list) {
String id = list2.get("UserID").toString();
String name = list2.get("UserName").toString();
Log.v("data", "id:" + id + " | name:" + name);
}
}
};

public static List<Map> getJSONObject(String path) throws Exception {
List<Map> list = new ArrayList<Map>();
Map map = null;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection對象,我們可以從網路中擷取網頁資料.
conn.setConnectTimeout(5 * 1000); // 單位是毫秒,設定逾時時間為5秒
conn.setRequestMethod("GET"); // HttpURLConnection是通過HTTP協議請求path路徑的,所以需要佈建要求方式,可以不設定,因為預設為GET
//Log.v("abc", "Status:"+conn.getResponseCode());

if (conn.getResponseCode() == 200) {// 判斷請求碼是否是200碼,否則失敗
InputStream is = conn.getInputStream(); // 擷取輸入資料流
byte[] data = readStream(is); // 把輸入資料流轉換成字元數組
String json = new String(data); // 把字元數群組轉換成字串


//資料形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"小豬"},{"id":2,"name":"小貓"}]}
JSONObject jsonObject=new JSONObject(json); //返回的資料形式是一個Object類型,所以可以直接轉換成一個Object
//int total=jsonObject.getInt("total");
Boolean success=jsonObject.getBoolean("success");
//Log.i("abc", "total:" + total + " | success:" + success); //測試資料


JSONArray jsonArray = jsonObject.getJSONArray("data");//裡面有一個數組資料,可以用getJSONArray擷取數組
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i); // 得到每個對象
int id = item.getInt("UserID"); // 擷取對象對應的值
String name = item.getString("UserName");

map = new HashMap(); // 存放到MAP裡面
map.put("UserID", id + "");
map.put("UserName", name);
list.add(map);
}
}

// ***********測試資料******************

for (Map list2 : list) {
String id = list2.get("UserID").toString();
String name = list2.get("UserName").toString();
Log.v("data", "id:" + id + " | name:" + name);
}

return list;
}


public static byte[] readStream(InputStream inputStream) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
bout.write(buffer, 0, len);
}
bout.close();
inputStream.close();

return bout.toByteArray();
}



public void Click2(View view)
{
Thread th=new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
String httpUrl = "http://apis.baidu.com/heweather/weather/free";
String httpArg = "city=beijing";
String jsonResult = request(httpUrl, httpArg);
Log.v("jsonResult",jsonResult);
//Toast.makeText(MainActivity.this, jsonResult, 0).show();
}
});

th.start();

}

/**
* @param urlAll
* :請求介面
* @param httpArg
* :參數
* @return 返回結果
*/
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;

try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
// 填入apikey到HTTP header
connection.setRequestProperty("apikey", "574cc9baa2b89769d89a6799c194f806");
connection.connect();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
Log.v("dituerr", e.toString());
e.printStackTrace();

}
return result;
}

}

 

 

:http://files.cnblogs.com/files/qujian15/GetHttpJsonData.rar

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.