android 获取http请求json数据 package com.my.gethttpjsondata; import java.io.BufferedReader; import java.

android 获取http请求json数据

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;
}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值