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