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;
}
}
下载地址:http://files.cnblogs.com/files/qujian15/GetHttpJsonData.rar
android 获取http请求json数据的更多相关文章
- Android - 使用Volley请求网络数据
Android - 使用Volley请求网络数据 Android L : Android Studio 14 个人使用volley的小记,简述使用方法,不涉及volley源码 准备工作 导入Volle ...
- JSONProxy - 获取跨域json数据工具
JSONProxy是一款很好的获取json数据的代理网站,“Enables cross-domain requests to any JSON API”.当你苦于无法跨域获取json数据时,不妨一试, ...
- AJAX跨域请求json数据的实现方法
这篇文章介绍了AJAX跨域请求json数据的实现方法,有需要的朋友可以参考一下 我们都知道,AJAX的一大限制是不允许跨域请求. 不过通过使用JSONP来实现.JSONP是一种通过脚本标记注入的方式, ...
- Jquery Ajax和getJSON获取后台普通Json数据和层级Json数据解析
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 关于使用Ajax请求json数据,@RequestMapping返回中文乱码的几种解决办法
一.问题描述: 使用ajax请求json数据的时候,无论如何返回的响应编码都是ISO-8859-1类型,因为统一都是utf-8编码,导致出现返回结果中文乱码情况. $.ajax({ type:&quo ...
- bootstrap通过ajax请求JSON数据后填充到模态框
1. JSP页面中准备模态框 <!-- 详细信息模态框(Modal) --> <div> <div class="modal fade" id=& ...
- react之fetch请求json数据
Fetch下载 npm install whatwg-fetch -S Fetch请求json数据 json文件要放在public内部才能被检索到
- ajax 请求json数据中json对象的构造获取问题
前端的界面中,我想通过ajax来调用写好的json数据,并调用add(data)方法进行解析,请求如下: json数据如下: { “type”:"qqq", "lat&q ...
- Android学习笔记之JSON数据解析
转载:Android学习笔记44:JSON数据解析 JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,为Web应用开发提供了一种 ...
随机推荐
- k-近邻算法 python实现
必要的注释已经写在code里面了: import operator from numpy import* def init(): grp=array([[1.0,1.1],[1.0,1.0],[0,0 ...
- string、char *的转换
string转char* 主要有三种方法可以将str转换为char*类型,分别是:data(); c_str(); copy(); data()方法 string str = "hello& ...
- 12个值得关注的顶级可视化JS库 涉及图表、动画、时间处理,表格操作
本文是译文,原文是https://da-14.com/blog/top-11...我在原文的基础上加了百度的Echats图表库,这个也是毫不逊色其他图表库的.另外Handsontable电子表格库也是 ...
- FPGA实战操作(2) -- PCIe总线(协议简述)
目录 1. PCIe基础知识 2. 事务层协议 2.1 数据包结构 2.2 帧头含义详述 3. 报文举例 3.1 寄存器读报文 3.2 完成报文 4. 机制简述 4.1 Non-Posted和Post ...
- linux 命令 htop & 重定向 top, bashrc文件
最近在用linux服务器跑程序,有几条linux命令还蛮重要的,总结一下: 1. 直接跑代码: python test.py 2. 若想程序在后台跑,即使本地和服务器断开也能运行: nohup pyt ...
- [转] CDH6 安装文章链接收集
CentOS 7下Cloudera Manager及CDH 6.0.1安装过程详解 http://blog.51cto.com/wzlinux/2321433?source=dra Cloudera ...
- 搭建类似生产环境的RAC
install the necessary packages yum install -y 创建组.用户和目录 创建用户组 groupadd -g 2000 oinstallgroupadd -g 2 ...
- WebDriver+TestNG的一个典型例子
想让测试更加灵活,1. 可以配置使用任意支持的浏览器进行测试:2. 配置所有Google的URL:3. 配置搜索的关键字.修改后的代码: public class GoogleTest { WebDr ...
- java线程状态 以及 sheep()、wait()、yield() 区别
前言 最近看到很多人都在讨论多线程的问题,于是写出了这篇博客,希望可以帮到正在学习和使用这块的朋友们,首先我们先看看两个图(两个图都来自其他码农的分享) 这两个图是一样的逻辑,这里一起罗列出来,下 ...
- emacs26.1 ppa
sudo add-apt-repository ppa:kelleyk/emacssudo apt updatesudo apt install emacs26