标签:网络 android asynctask android json 登录
2.JSON的使用
3.检查网络连接
4.AsyncTask的使用
我们简单的以登录为例,来实现整个的流程。话不多说,先来看看效果图:
/** * Created by Hyman on 2015/6/11. */ public class CallService { /** * check net connection before call * * @param context * @return */ private static boolean checkNet(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { // 获取网络连接管理的对象 NetworkInfo info = connectivity.getActiveNetworkInfo(); if (info != null && info.isConnected()) { // 判断当前网络是否已经连接 if (info.getState() == NetworkInfo.State.CONNECTED) { return true; } } } return false; } /** * call service by net * * @param urlString url * @param content a string of json,params * @return the result,a string of json */ public static String call(String urlString, String content, Context context) { if (!checkNet(context)) { return null; } try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "Fiddler"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Charset", "utf-8"); OutputStream os = conn.getOutputStream(); os.write(content.getBytes()); os.close(); int code = conn.getResponseCode(); if (code == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); String retData; String responseData = ""; while ((retData = in.readLine()) != null) { responseData += retData; } in.close(); return responseData; } } catch (MalformedURLException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static void showNetErr(Context context){ new AlertDialog.Builder(context) .setTitle("网络错误") .setMessage("网络连接失败,请确认网络连接") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { } }).show(); } }
/** * Created by Hyman on 2015/6/11. */ public class Login { private static final String urlString = GetServerUrl.getUrl() + "index.php?r=period/login"; private static final String TAG = "Login"; private ProgressBar progressBar; private Context context; private String userName; private String password; public Login( Context context,ProgressBar progressBar) { this.progressBar=progressBar; this.context = context; } public void login(String userName,String password) { Log.i(TAG, "call login"); this.userName=userName; this.password=password; new LoginTask().execute(); } class LoginTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { JSONObject tosendsObject = new JSONObject(); Log.i(TAG, "start put json!"); try { //add account info tosendsObject.put("username", userName); tosendsObject.put("password", password); } catch (JSONException e) { e.printStackTrace(); } //change json to String String content = String.valueOf(tosendsObject); Log.i(TAG, "send :" + content); String responseData = CallService.call(urlString, content,context); if(responseData==null || responseData.equals("")){ return null; } Log.i(TAG, "res:" + responseData); JSONObject resultObject = null; String result=null; try { resultObject = new JSONObject(responseData); result = resultObject.getString("result"); Log.i(TAG, "result:" + result); } catch (JSONException e) { e.printStackTrace(); } return result; } @Override protected void onPreExecute() { progressBar.setVisibility(View.VISIBLE); //show the progressBar super.onPreExecute(); } @Override protected void onPostExecute(String result) { progressBar.setVisibility(View.GONE); //hide the progressBar if(result==null){ CallService.showNetErr(context); return; } Toast.makeText(context,"result:"+result,Toast.LENGTH_SHORT).show(); //here you can do anything you want after login } } }
JSONArray jsonArray = new JSONArray(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); try { for (PeriodPO peroid : localPeriods) { //这是一个我自定义的数据结构的list JSONObject periodObject = new JSONObject(); periodObject.put("date", sdf.format(peroid.getDate())); periodObject.put("tag", peroid.getTag()); periodObject.put("length", peroid.getLength()); jsonArray.put(periodObject); //把每一个对象转成JsonObject,再把每个object放入Array } tosendsObject.put("periods", jsonArray); //add account info tosendsObject.put("username", "test"); } catch (JSONException e) { e.printStackTrace(); }
标签:网络 android asynctask android json 登录
原文地址:http://blog.csdn.net/u012422829/article/details/46491779