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应用开发提供了一种 ...
随机推荐
- leetcode-686-Repeated String Match(重复多少次A能够找到B)
题目描述: Given two strings A and B, find the minimum number of times A has to be repeated such that B i ...
- 类型转换 / BOOL 类型
/* Swift不允许隐式类型转换, 但可以使用显示类型转换(强制类型转换) OC: int intValue = 10; double doubleValue = (double)intValue; ...
- 根据域名获取ip地址gethostbyname
#include <sys/socket.h> #include <stdio.h> #include <netdb.h> int main(int argc, c ...
- 利用ReentrantLock简单实现一个阻塞队列
借助juc里的ReentrantLock实现一个阻塞队列结构: package demo.concurrent.lock.queue; import java.util.concurrent.lock ...
- SpringMVC 的 切面
官网路径:https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans 一:术语介绍 通知 ...
- dubbo集群容错之LoadBalance
原文地址:Dubbo 源码分析 - 集群容错之 LoadBalance dubbo 提供了4种负载均衡实现,分别是基于权重随机算法的 RandomLoadBalance.基于最少活跃调用数算法的 Le ...
- 关闭mac自带apache的启动。
关闭mac自带apache的启动. sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist 如果哪天 ...
- 高性能的数据压缩库libzling-20140324
libzling(https://github.com/richox/libzling,求观看[watch],求星[star],求叉[fork])是一款高性能的数据压缩库,在压缩时间和压缩率上都超过了 ...
- 解决UnicodeDecodeError: 'ascii' code can't decode byte 0xef in position
今天在使用python的pip安装的时候出现了这个错误 UnicodeDecodeError: 'ascii' code can't decode byte 0xef in position 7: o ...
- 字符编码的来源,ascii、unicode和utf-8编码的关系
字符编码 我们已经讲过了,字符串也是一种数据类型,但是,字符串比较特殊的是还有一个编码问题. 因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理.最早的计算机在设计时采用8个比特 ...