在Android开发中,我们或多或少都会需要用到请求,获取JSON和解析JSON,来获取有用的数据,这里我们可以写些小实例来帮助那些入门的初学者,少走学习的歪
路,节约更多时间往其他方向学习和发展
我就写一个登录接口的小应用,我只做了JSON抓取,而没做解析了,因为是测试用的
MainActivity :
package com.jdys; import java.io.IOException; import org.apache.http.client.ClientProtocolException; import org.json.JSONException; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; public class MainActivity extends Activity { // username edittext private EditText ed_user; // password edittext private EditText ed_pwd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Instantiated user ed_user = (EditText)findViewById(R.id.user); //Instantiated pwd ed_pwd = (EditText)findViewById(R.id.pwd); } // OK clickbotton public void Login(View v) throws Exception{ String time = (""+System.currentTimeMillis()).substring(0,10); String user = ed_user.getText().toString(); String pwd = ed_pwd.getText().toString(); LoginAPI.LOGIN_REQUEST_URL = LoginAPI.LOGIN_REQUEST_URL.replace("TIMESTAMP", time); LoginAPI.LOGIN_REQUEST_URL = LoginAPI.LOGIN_REQUEST_URL.replace("USERNAME", user); LoginAPI.LOGIN_REQUEST_URL = LoginAPI.LOGIN_REQUEST_URL.replace("PASSWORD", pwd); Log.d("XXXXXXXXXXXXXXXX", "时间戳:"+time+" "+"账户:"+user+" "+"密码:"+pwd+"\n"+LoginAPI.LOGIN_REQUEST_URL); // 发送请求获取数据 new Thread(){ @Override public void run() { super.run(); try { String jsonObject = LoginService.httpRequest(LoginAPI.LOGIN_REQUEST_URL); Log.d("XXXXXXXXXXXXXXXX", "返回的数据:"+jsonObject); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } public static boolean checkNetworkAvailable(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { System.out.println(" ######### 网络链接错误 ############### "); return false; } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { NetworkInfo netWorkInfo = info[i]; if (netWorkInfo.getType() == ConnectivityManager.TYPE_WIFI) { return true; } else if (netWorkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { return true; } } } } } return false; } }
package com.jdys; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONException; import android.util.Log; public class LoginService { public static String httpRequest(String requestURL) throws ClientProtocolException, IOException, JSONException{ StringBuffer buffer = new StringBuffer(); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(requestURL); HttpResponse response = client.execute(get); if(response.getStatusLine().getStatusCode()==LoginAPI.HTTP_STATS){ buffer.append(EntityUtils.toString(response.getEntity(),"UTF-8")); }else{ Log.d("XXXXXXXXXXXXXXXX", "获取数据失败!"); } return buffer.toString(); } }
运行结果:
需要注意的是,在 MainActivity 的 LoginService.httpRequest()方法需要放到新(子)线程里执行网络操作,因为在Android SDK 4.0及以上在主活动(此篇日志为MainActivity)里进行网络操作,需要在子线程里执行,否则会抛出 NetworkOnMainThreadException 异常
请大家引起注意~