android发送json数据
❶ android怎么看json数据格式
JSON有两种表示结构,对象和数组。
对象结构以”{”大括号开始,以”}”大括号结束。中间部分由0或多个以”,”分隔的”key(关键字)/value(值)”对构成,关键字和值之间以”:”分隔,语法结构如下
{
key1:value1,
key2:value2,
}其中关键字是字符串,而值可以是字符串,数值,true,false,null,对象或数组
数组结构以”[”开始,”]”结束。中间由0或多个以”,”分隔的值列表组成,语法结构如下
[
{
key1:value1,
key2:value2
},
{
key3:value3,
key4:value4
}
]
❷ android怎么得到php发来的json数据
使用守则
首先,我们要创建Web服务,从Mysql数据库中读取数据。
<?php
<pre>/* require the user as the parameter */
<pre>//http://localhost:8080/sample1/webservice1.php?user=1
if(isset($_GET['user']) && intval($_GET['user'])) {
/* soak in the passed variable or set our own */
$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
$user_id = intval($_GET['user']); //no default
/* connect to the db */
$link = mysql_connect('localhost','root','123456') or die('Cannot connect to the DB');
mysql_select_db('TEST',$link) or die('Cannot select the DB');
/* grab the posts from the db */
//$query = "SELECT post_title, guid FROM wp_posts WHERE post_author =
// $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
$query = "SELECT * FROM `test`.`users`;";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
}
}
/* output in necessary format */
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
}
else {
header('Content-type: text/xml');
echo '';
foreach($posts as $index => $post) {
if(is_array($post)) {
foreach($post as $key => $value) {
echo '<',$key,'>';
if(is_array($value)) {
foreach($value as $tag => $val) {
echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
}
}
echo '</',$key,'>';
}
}
}
echo '';
}
/* disconnect from the db */
@mysql_close($link);
}
?>
下面是代码为Android活动读取Web服务和解析JSON对象:
public void clickbutton(View v) {
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("user", "1");
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8080/sample1/" +
"webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("isers", jObject.getString("isers"));
map.put("UserName", jObject.getString("UserName"));
map.put("FullName", jObject.getString("FullName"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
这里是PHP代码,将数据发送到Web服务,并将其保存:
<?php
//$json=$_GET ['json'];
$json = file_get_contents('php://input');
$obj = json_decode($json);
//echo $json;
//Save
$con = mysql_connect('localhost','root','123456')
or die('Cannot connect to the DB');
mysql_select_db('TEST',$con);
/* grab the posts from the db */
//$query = "SELECT post_title, guid FROM wp_posts WHERE
// post_author = $user_id AND post_status = 'publish'
// ORDER BY ID DESC LIMIT $number_of_posts";
mysql_query("INSERT INTO `test`.`users` (UserName, FullName)
VALUES ('".$obj->{'UserName'}."', '".$obj->{'FullName'}."')");
mysql_close($con);
//
//$posts = array($json);
$posts = array(1);
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
?>
Android的活动,将数据发送到Web服务作为一个JSON对象保存在MySQL数据库中
public void clickbuttonRecieve(View v) {
try {
JSONObject json = new JSONObject();
json.put("UserName", "test2");
json.put("FullName", "1234567"); HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://10.0.2.2:8080/sample1/webservice2.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
Toast.makeText(this, result,
Toast.LENGTH_LONG).show();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
知识点
要连接到你的模拟器,你可以使用此链接:http://10.0.2.2:8080/。
要读取JSON对象在Web服务中,您可以使用下面这行代码:
$json = file_get_contents('php://input');
$obj = json_decode($json);
❸ Android studio使用Retrofit框架,Get发送请求,Gson解析返回的json数据时报错怎么办
数据库一直以来给我的感觉就是——麻烦!!!
接触了Realm之后才终于可以开开心心的使用数据库了。
本文总结一些Realm数据库的常用知识点,包括多线程访问,以及如何与Retrofit2.0一起使用等...
看懂这些知识点之后,个人认为就可以在一般的项目中使用Realm了。
1. model类必须extends RealmObject,所有属性必须用private修饰
2. model中支持基本数据结构:boolean, byte, short, ìnt, long, float, double, String, Dateand byte[]
3.若要使用List必须用RealmList<T>,或者继承RealmList
4.与Retrofit2.*一起使用,通过Gson来解析Json数据并直接生成RealmObject,可参考如下写法:
[java] view plain
Gson gson = new GsonBuilder()
.setExclusionStrategies(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getDeclaringClass().equals(RealmObject.class);
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
❹ android post请求json参数list认证怎样实现
如果采用post请求,与后台传送参数采用json格式,那么可以采用如下的形式包装参数:
JSONObject params = new JSONObject();
params.put("signature",signature);
params.put("timestamp",timestamp);
params.put("nouce",nouce);
params.put("parnter",parnter);
params.put("access_token",access_token);
包装之后可以采用一个访问网络的工具类HttpClient访问后台接口就可以了
我不知道你说的是不是这个意思,希望帮到你
❺ android怎么使用okhttputils发送json请求数据
服务端是用servlet写的吧 直接调用response的out输出即可 response.getWriter().print("20"); 这样安卓得到的返回值就是20
❻ android volley stringrequest post中的getparams怎么把json数据提交上去
1.客户端以普通的post方式进行提交,服务端返回字符串
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST,httpurl,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "response -> " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.getMessage(), error);
}
}) {
@Override
protected Map<String, String> getParams() {
//在这里设置需要post的参数
Map<String, String> map = new HashMap<String, String>();
map.put("name1", "value1");
map.put("name2", "value2");
return params;
}
};
requestQueue.add(stringRequest);
2.客户端以json串的post请求方式进行提交,服务端返回json串
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
Map<String, String> map = new HashMap<String, String>();
map.put("name1", "value1");
map.put("name2", "value2");
JSONObject jsonObject = new JSONObject(params);
JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Method.POST,httpurl, jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, "response -> " + response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, error.getMessage(), error);
}
})
{
//注意此处override的getParams()方法,在此处设置post需要提交的参数根本不起作用
//必须象上面那样,构成JSONObject当做实参传入JsonObjectRequest对象里
//所以这个方法在此处是不需要的
// @Override
// protected Map<String, String> getParams() {
// Map<String, String> map = new HashMap<String, String>();
// map.put("name1", "value1");
// map.put("name2", "value2");
// return params;
// }
❼ android 在服务器端生成json格式数据,在客户端怎么解析
1、生成JSON格式数据,有对应的后台类处理,如果你是做Android开发,后台提供获取数据的接口
2、客户端解决:
JSONArrayjsonArr=newJSONArray(json);
for(inti=0;i<jsonArr.length();i++){
JSONObjectjsonObj=jsonArr.getJSONObject(i);
booleanisChild=jsonObj.has("childrenNodes");
AreaBeanbean=newAreaBean(jsonObj.getString("id"),
jsonObj.getString("parentId"),
jsonObj.getString("name"));
mList.add(bean);
if(isChild){
mchildNodesList.add(jsonObj.getString("childrenNodes"));
}else{
mchildNodesList.add(null);
}
}