做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教程有興趣的朋友有所協助。