Android学习笔记:在Android平台上通过JSON格式与服务器端进行数据交互


[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">要求:</span>  
Android编写一个登录界面,输入用户名和密码,使用JSON格式提交到服务器端。
服务器端收到后返回(JSON格式数据):
“输入的用户”+您好,你已成功登录系统。

其实不管是JSON还是其他类型,都是为了满足Android与服务器端的程序进行数据交换的要求而已
本次笔记的个人觉得 重点如下:
1.服务器端的数据接收 
1)包括数据编码的设定
发送与接受最好都用utf-8来设定编码来
在doPost中加入Response声明
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <span style="white-space:pre">  </span>response.setCharacterEncoding("UTF-8");  
  2. <span style="white-space:pre">  </span>response.setContentType("UTF-8");  

2)了解异步线程的用途与如何用异步线程AsyncTask 来更新UI
首先,什么时候需要用到异步线程呢,在需要进行对网络发送接收稍大量的数据的时候,或者占用稍大时间,影响了用户体验而又不是必要的等待时间时,就要用到异步。
然后异步线程的大概用法是这样:
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public class JSONOperation extends AsyncTask<JSONObject, Void, String>  

这里第一个参数是指 发送给这个线程的数据类型 第二个是后台任务执行的进度、后台计算结果的类型。
里面重写的doInBackgroud(JSONObject... JSONObjs) 就是执行的函数,主要用来执行任务主要内容(在这个例子中主要是进行与服务器端的JSON数据包发送与接受,但不包括对Activity的UI更新操作)。然后可以通过返回一个类型的值比如返回一个String或者JSONObject来给下面重写的onPostExecute方法进行对ActivityUI的更新。
比如说  protected String doInBackground(JSONObject... JSONObjs) 方法 发送到服务器端,并且服务器又发送了一个JSON数据包回来,然后这个方法就可以return这个JSON数据包
然后在下面的onPostExecute(JSONObject obj)就对刚刚doInBackground中的JSONObject类型进行引用,在里面可以添加对UI的操作比如TextView的更新什么的。
如果在doInBackground中执行UI更新操作,就会返回android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.  
这个错误意思是 只有原始创建这个视图层次(view hierachy)的线程才能修改它的视图(view)



实现:
Servlet中的doPost代码
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  2.             throws ServletException, IOException {  
  3.         response.setCharacterEncoding("UTF-8");  
  4.         response.setContentType("UTF-8");  
  5.         StringBuffer sb = new StringBuffer("");  
  6.         String result = "";  
  7.         try {  
  8.             BufferedReader br = new BufferedReader(new InputStreamReader(  
  9.                     request.getInputStream(), "utf-8"));  
  10.             String temp;  
  11.             while ((temp = br.readLine()) != null) {  
  12.                 sb.append(temp);  
  13.             }  
  14.             br.close();  
  15.             result = sb.toString();  
  16.             //打印android端上传的JSON数据  
  17.             System.out.println(result);  
  18.         } catch (Exception e) {  
  19.             e.printStackTrace();  
  20.         }  
  21.         JSONObject jsonObject = JSONObject.fromObject(result);  
  22.         String name = jsonObject.getString("username");  
  23.         String password=jsonObject.getString("password");  
  24.         PrintWriter pw = response.getWriter();  
  25.         //封装服务器返回的JSON对象  
  26.         JSONObject jsonReply = new JSONObject();  
  27.         jsonReply.put("ConnectName",name);  
  28.         jsonReply.put("ConnectPass", password);  
  29.         //打印返回的JSON数据  
  30.         System.out.println(jsonReply);  
  31.         //pw.write("连接成功!");  
  32.         //BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(jsonReply."utf-8"));  
  33.         pw.write(jsonReply.toString());  
  34.         pw.flush();  
  35.         pw.close();  
  36.     }  



==Android==
1.别忘了添加网络权限
2.别忘了修改ip地址 Address
界面代码:
[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:id="@+id/RelativeLayout1"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:orientation="vertical"  
  7.     android:paddingBottom="@dimen/activity_vertical_margin"  
  8.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  9.     android:paddingRight="@dimen/activity_horizontal_margin"  
  10.     android:paddingTop="@dimen/activity_vertical_margin"  
  11.     tools:context=".Main" >  
  12.   
  13.     <TextView  
  14.         android:id="@+id/TextView_UserName"  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.         android:layout_alignParentLeft="true"  
  18.         android:layout_alignParentTop="true"  
  19.         android:layout_marginLeft="20dp"  
  20.         android:layout_marginTop="22dp"  
  21.         android:text="@string/String_UserName" />  
  22.   
  23.     <EditText  
  24.         android:id="@+id/EditText_UserName"  
  25.         android:layout_width="match_parent"  
  26.         android:layout_height="wrap_content"  
  27.         android:layout_alignBaseline="@+id/TextView_UserName"  
  28.         android:layout_alignBottom="@+id/TextView_UserName"  
  29.         android:layout_toRightOf="@+id/TextView_UserName"  
  30.         android:ems="10"  
  31.         android:inputType="text" >  
  32.   
  33.         <requestFocus />  
  34.     </EditText>  
  35.   
  36.     <TextView  
  37.         android:id="@+id/TextView_PassWord"  
  38.         android:layout_width="wrap_content"  
  39.         android:layout_height="wrap_content"  
  40.         android:layout_below="@+id/EditText_UserName"  
  41.         android:layout_marginTop="42dp"  
  42.         android:layout_toLeftOf="@+id/EditText_UserName"  
  43.         android:text="@string/String_PassWord" />  
  44.      
  45.     <EditText  
  46.         android:id="@+id/EditText_PassWord"  
  47.         android:layout_width="match_parent"  
  48.         android:layout_height="wrap_content"  
  49.         android:layout_alignBaseline="@+id/TextView_PassWord"  
  50.         android:layout_alignBottom="@+id/TextView_PassWord"  
  51.         android:layout_toRightOf="@+id/TextView_PassWord"  
  52.         android:ems="10"  
  53.         android:inputType="textPassword" >  
  54.   
  55.         <requestFocus />  
  56.     </EditText>  
  57.   
  58.     <Button  
  59.         android:id="@+id/Button_Login"  
  60.         android:layout_width="wrap_content"  
  61.         android:layout_height="wrap_content"  
  62.         android:layout_below="@+id/EditText_PassWord"  
  63.         android:layout_centerHorizontal="true"  
  64.         android:layout_marginTop="34dp"  
  65.         android:text="@string/String_Login" />  
  66.   
  67.     <TextView  
  68.         android:id="@+id/TextView_Result"  
  69.         android:layout_width="match_parent"  
  70.         android:layout_height="180dp"  
  71.         android:layout_below="@+id/Button_Login"  
  72.         android:layout_centerHorizontal="true"  
  73.         android:layout_marginTop="32dp"  
  74.         android:text="@string/String_Result" />  
  75.   
  76. </RelativeLayout>  

Activity
[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package bnuz.alt.wechat;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.UnsupportedEncodingException;  
  6.   
  7. import org.apache.http.HttpEntity;  
  8. import org.apache.http.HttpResponse;  
  9. import org.apache.http.client.ClientProtocolException;  
  10. import org.apache.http.client.HttpClient;  
  11. import org.apache.http.client.methods.HttpPost;  
  12. import org.apache.http.entity.StringEntity;  
  13. import org.apache.http.impl.client.DefaultHttpClient;  
  14. import org.apache.http.util.EntityUtils;  
  15. import org.json.JSONException;  
  16. import org.json.JSONObject;  
  17.   
  18. import android.os.AsyncTask;  
  19. import android.os.Bundle;  
  20. import android.app.Activity;  
  21. import android.util.Log;  
  22. import android.view.Menu;  
  23. import android.view.View;  
  24. import android.view.View.OnClickListener;  
  25. import android.widget.Button;  
  26. import android.widget.EditText;  
  27. import android.widget.TextView;  
  28. import android.widget.Toast;  
  29.   
  30. public class Main extends Activity {  
  31.     private EditText ET_UserName, ET_PassWord;  
  32.     private TextView TV_Result;  
  33.     private Button BT_Login;  
  34.     private String UserName, PassWord;  
  35.     private static final String ServerAddress = "http://113.103.144.143:8080/ServerJsonDemo/servlet/JsonServlet",  
  36.         TAG = "ATag";  
  37.     private String Result_FromServer;  
  38.     private JSONObject JsonObj;  
  39.   
  40.     @Override  
  41.     protected void onCreate(Bundle savedInstanceState) {  
  42.     super.onCreate(savedInstanceState);  
  43.     setContentView(R.layout.activity_main);  
  44.   
  45.     ET_UserName = (EditText) findViewById(R.id.EditText_UserName);  
  46.     ET_PassWord = (EditText) findViewById(R.id.EditText_PassWord);  
  47.     TV_Result = (TextView) findViewById(R.id.TextView_Result);  
  48.     BT_Login = (Button) findViewById(R.id.Button_Login);  
  49.   
  50.     BT_Login.setOnClickListener(new OnClickListener() {  
  51.   
  52.         @Override  
  53.         public void onClick(View v) {  
  54.         UserName = ET_UserName.getText().toString();  
  55.         PassWord = ET_PassWord.getText().toString();  
  56.         JsonObj = makeUserInfo(UserName, PassWord);  
  57.         if (UserName.equals("")) {  
  58.             Toast.makeText(getApplicationContext(), "请输入用户名",  
  59.                 Toast.LENGTH_LONG).show();  
  60.         }  
  61.         if (PassWord.equals("")) {  
  62.             Toast.makeText(getApplicationContext(), "请输入密码",  
  63.                 Toast.LENGTH_LONG).show();  
  64.         }  
  65.         if (!PassWord.equals("") && !UserName.equals("")) {  
  66.             Toast.makeText(getApplicationContext(), "登陆中...",  
  67.                 Toast.LENGTH_LONG).show();  
  68.             JSONOperation sendJsonTask = new JSONOperation();  
  69.             sendJsonTask.execute(JsonObj);  
  70.   
  71.         }  
  72.         }  
  73.   
  74.     });  
  75.     }  
  76.   
  77.     @Override  
  78.     public boolean onCreateOptionsMenu(Menu menu) {  
  79.     getMenuInflater().inflate(R.menu.main, menu);  
  80.     return true;  
  81.     }  
  82.   
  83.     public JSONObject makeUserInfo(String userName, String passWord) {  
  84.     JSONObject UserInfo = new JSONObject();  
  85.     try {  
  86.         UserInfo.put("username", userName);  
  87.         UserInfo.put("password", passWord);  
  88.     } catch (JSONException e) {  
  89.         throw new RuntimeException(e);  
  90.     }  
  91.     return UserInfo;  
  92.     }  
  93.   
  94.     public void UpdateResult(String connectName, String connectPass) {  
  95.     TV_Result.append("\n用户名:" + connectName + "\n密码" + connectPass);  
  96.     }  
  97.   
  98.     public class JSONOperation extends AsyncTask<JSONObject, Void, String> {  
  99.   
  100.     @Override  
  101.     protected String doInBackground(JSONObject... JSONObjs) {  
  102.         String Result_Show = null;  
  103.         HttpClient httpclient = new DefaultHttpClient();  
  104.         HttpPost httppost = new HttpPost(ServerAddress);  
  105.         try {  
  106.         httppost.setEntity(new StringEntity(JsonObj.toString()));  
  107.         HttpResponse httpres = httpclient.execute(httppost);  
  108.   
  109.         if (httpres.getStatusLine().getStatusCode() == 200) {  
  110.             Log.d(TAG, "成功连接信号");  
  111.             String Res = EntityUtils.toString(httpres.getEntity());  
  112.             JSONObject JsonResult = new JSONObject(Res);  
  113.             // String Result_Name = JsonResult.getString("ConnectName");  
  114.             // String Result_PassWord = JsonResult  
  115.             // .getString("ConnectPass");  
  116.             Result_Show = JsonResult.toString();  
  117.             Log.d(TAG,Result_Show);  
  118.         }  
  119.           
  120.         } catch (Exception e) {  
  121.         Log.d(TAG, e.toString());  
  122.         }  
  123.         return Result_Show;  
  124.     }  
  125.   
  126.     @Override  
  127.     protected void onPostExecute(String result) {  
  128.         TV_Result.append("\n"+result);  
  129.         TV_Result.append("\n你好,你已經成功登陸系統");  
  130.         super.onPostExecute(result);  
  131.   
  132.     }  
  133.     }  
  134. }  


效果图:

Servlet端


Android
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值