时间:2021-07-01 10:21:17 帮助过:21人阅读
做这个项目,我们要用到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);
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
以上就介绍了Android访问php调取json数据,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。