做android项目,离不开去服务器取数据,典型的就是android访问php调取json数据。网上类似的例子一大堆,而且居然代码都一样,我要吐槽一下,你们发的代码不全,这不是坑人吗。
做这个项目,我们要用到apache提供的依赖包(jar包):①httpclient ②httpcore ③http-mimi ④apache-mime4j
国际惯例:先上demo,下载地址:android访问php调取json数据
我们先熟悉一下 php下的json数据格式
e.g.
$tnnowu = array(
‘username’ => ‘灬抹茶灬’,
‘password’ => ‘666’,
‘user_id’ => 1
);
echo json_encode($tnnowu);接着我们编写java代码
mainactivity.java
package com.cnwuth.getjson;
import android.support.v7.app.appcompatactivity;
import android.os.bundle;
import android.util.log;
import org.apache.http.httpresponse;
import org.apache.http.client.httpclient;
import org.apache.http.client.methods.httpget;
import org.apache.http.impl.client.defaulthttpclient;
import org.json.jsonobject;
import java.io.bufferedreader;
import java.io.inputstreamreader;
public class mainactivity extends appcompatactivity{
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
}
private void starturlcheck(string username,string password)
{
httpclient httpclient = new defaulthttpclient();
stringbuilder stringbuilder = new stringbuilder();
httpget httpget = new httpget(“xxx.xxx.php”);
try
{
httpresponse httpresponse = httpclient.execute(httpget);
bufferedreader bufferedreader = new bufferedreader(new inputstreamreader(
httpresponse.getentity().getcontent()
));
for (string s = bufferedreader.readline();s!=null;s=bufferedreader.readline())
{
stringbuilder.append(s);
}
jsonobject jsonobject = new jsonobject(stringbuilder.tostring());
string re_username = jsonobject.getstring(“username”);
string re_password = jsonobject.getstring(“password”);
int re_user_id = jsonobject.getint(“user_id”);
settitle(“用户id_” + re_user_id);
log.v(“url response” , “true=” + re_username);
log.v(“url response” , “true=” + re_password);
}
catch (exception e)
{
log.v(“url response” , “false”);
e.printstacktrace();
}
}
}最后,需要网络权限才可以访问数据
androidmainifest.xml
关注我的最新动态;新浪微博 @吴天昊tnnowu
以上就介绍了android访问php调取json数据,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。