HTTP服务器与Android客户端的json交互



废话就不多说了,直接上代码:

服务器端:


MySQL中建立一个数据库hello,建一张表tab_user,添加字段id,username,password。然后随便添加几条记录。

②新建Java Web工程HelloServer。

③在WEB-INF目录下的lib中引入mysql-connector-java-5.0.8-bin.jar与org.json.jar。

④新建Servlet类LoginServlet。

LoginServlet.java:

[java]  view plain  copy
  1. package cn.domain.hello.servlet;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.io.PrintWriter;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12. import org.json.JSONArray;  
  13. import org.json.JSONObject;  
  14. import cn.domain.hello.bean.UserBean;  
  15. import cn.domain.hello.dao.UserDao;  
  16.   
  17. public class LoginServlet extends HttpServlet {  
  18.   
  19.     /** 
  20.      *  
  21.      */  
  22.     private static final long serialVersionUID = 1L;  
  23.   
  24.     /** 
  25.      * The doGet method of the servlet. <br> 
  26.      *  
  27.      * This method is called when a form has its tag value method equals to get. 
  28.      *  
  29.      * @param request 
  30.      *            the request send by the client to the server 
  31.      * @param response 
  32.      *            the response send by the server to the client 
  33.      * @throws ServletException 
  34.      *             if an error occurred 
  35.      * @throws IOException 
  36.      *             if an error occurred 
  37.      */  
  38.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  39.             throws ServletException, IOException {  
  40.         doPost(request, response);  
  41.     }  
  42.   
  43.     /** 
  44.      * The doPost method of the servlet. <br> 
  45.      *  
  46.      * This method is called when a form has its tag value method equals to 
  47.      * post. 
  48.      *  
  49.      * @param request 
  50.      *            the request send by the client to the server 
  51.      * @param response 
  52.      *            the response send by the server to the client 
  53.      * @throws ServletException 
  54.      *             if an error occurred 
  55.      * @throws IOException 
  56.      *             if an error occurred 
  57.      */  
  58.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  59.             throws ServletException, IOException {  
  60.         request.setCharacterEncoding("UTF-8");  
  61.         response.setContentType("text/json;charset=UTF-8");  
  62.         String reqMessage, respMessage;  
  63.         JSONArray reqObject = null;  
  64.         JSONArray respObject = null;  
  65.         try {  
  66.             BufferedReader br = new BufferedReader(new InputStreamReader(  
  67.                     request.getInputStream(), "UTF-8"));  
  68.             StringBuffer sb = new StringBuffer("");  
  69.             String temp;  
  70.             while ((temp = br.readLine()) != null) {  
  71.                 sb.append(temp);  
  72.             }  
  73.             br.close();  
  74.             reqMessage = sb.toString();  
  75.             System.out.println("请求报文:" + reqMessage);  
  76.             reqObject = new JSONArray(reqMessage);  
  77.             UserDao userDao = new UserDao();  
  78.             UserBean ub = userDao.getUserByName(reqObject.getJSONObject(0)  
  79.                     .getString("username"));  
  80.             if (ub.getPassword() != null  
  81.                     && ub.getPassword().equals(  
  82.                             reqObject.getJSONObject(0).getString("password"))) {  
  83.                 respObject = new JSONArray().put(new JSONObject().put("userId",  
  84.                         ub.getId()));  
  85.             }  
  86.         } catch (Exception e) {  
  87.             e.printStackTrace();  
  88.         } finally {  
  89.             respMessage = respObject == null ? "" : respObject.toString();  
  90.             System.out.println("返回报文:" + respMessage);  
  91.             PrintWriter pw = response.getWriter();  
  92.             pw.write(respMessage);  
  93.             pw.flush();  
  94.             pw.close();  
  95.         }  
  96.     }  
  97.   
  98. }  


简单抽象出了数据访问层,并实现数据库的操作,目录结构如下,由于文件多,详细请下载下面的源码查看:




好了,到这里服务器端就已经建立完成了。客户端访问这个servlet的URL为:http://10.0.2.2:8080/HelloServer/servlet/LoginServlet。

记住,在Android中localhost指的是模拟器本身,而这里的10.0.2.2指你的计算机服务器本地测试IP,可改成内网或外网IP。


Android客户端端:


①新建一个android application:Hello。

②引入org.json.jar。

③在activity_main.xml布局文件中加入两个EditText,来输入用户名和密码,添加按钮来提交json数据。

④先封装一下访问网络的HTTP操作:

WebUtil.java:

[java]  view plain  copy
  1. package cn.domain.hello.util;  
  2.   
  3. import org.apache.http.HttpResponse;  
  4. import org.apache.http.client.HttpClient;  
  5. import org.apache.http.client.methods.HttpPost;  
  6. import org.apache.http.entity.StringEntity;  
  7. import org.apache.http.impl.client.DefaultHttpClient;  
  8. import org.apache.http.params.BasicHttpParams;  
  9. import org.apache.http.params.HttpParams;  
  10. import org.apache.http.util.EntityUtils;  
  11. import org.json.JSONArray;  
  12.   
  13. import cn.domain.hello.config.Config;  
  14.   
  15. public class WebUtil {  
  16.     public static JSONArray getJSONArrayByWeb(String methodName,  
  17.             JSONArray params) {  
  18.   
  19.         String returnValue = "";  
  20.         JSONArray result = null;  
  21.         HttpParams httpParams = new BasicHttpParams();  
  22.         httpParams.setParameter("charset""UTF-8");  
  23.         HttpClient hc = new DefaultHttpClient(httpParams);  
  24.         HttpPost hp = new HttpPost(Config.SERVER_IP + "/HelloServer/servlet/"  
  25.                 + methodName);  
  26.         try {  
  27.             hp.setEntity(new StringEntity(params.toString(), "UTF-8"));  
  28.             HttpResponse hr = hc.execute(hp);  
  29.             if (hr.getStatusLine().getStatusCode() == 200) {  
  30.                 returnValue = EntityUtils.toString(hr.getEntity(), "UTF-8");  
  31.                 result = new JSONArray(returnValue);  
  32.             }  
  33.         } catch (Exception e) {  
  34.             // TODO Auto-generated catch block  
  35.             e.printStackTrace();  
  36.         }  
  37.         if (hc != null) {  
  38.             hc.getConnectionManager().shutdown();  
  39.         }  
  40.         return result;  
  41.     }  
  42. }  
⑤在MainActivity中实现登录操作:

[java]  view plain  copy
  1. package cn.domain.hello.activity;  
  2.   
  3. import org.json.JSONArray;  
  4. import org.json.JSONException;  
  5. import org.json.JSONObject;  
  6.   
  7. import cn.domain.hello.R;  
  8. import cn.domain.hello.config.Config;  
  9. import cn.domain.hello.util.WebUtil;  
  10. import android.app.Activity;  
  11. import android.os.AsyncTask;  
  12. import android.os.Bundle;  
  13. import android.util.Log;  
  14. import android.view.View;  
  15. import android.view.ViewStub;  
  16. import android.view.View.OnClickListener;  
  17. import android.view.ViewGroup;  
  18. import android.widget.Button;  
  19. import android.widget.EditText;  
  20. import android.widget.TextView;  
  21. import android.widget.Toast;  
  22.   
  23. public class MainActivity extends Activity {  
  24.   
  25.     private EditText etUsername;  
  26.     private EditText etPassword;  
  27.     private Button btnLogin;  
  28.     private ViewGroup vsProgress;  
  29.   
  30.     @Override  
  31.     protected void onCreate(Bundle savedInstanceState) {  
  32.         super.onCreate(savedInstanceState);  
  33.         setContentView(R.layout.activity_main);  
  34.         this.etUsername = (EditText) this.findViewById(R.id.etUsername);  
  35.         this.etPassword = (EditText) this.findViewById(R.id.etPassword);  
  36.         this.btnLogin = (Button) this.findViewById(R.id.btnLogin);  
  37.         this.btnLogin.setOnClickListener(new OnClickListener() {  
  38.   
  39.             @Override  
  40.             public void onClick(View v) {  
  41.                 // TODO Auto-generated method stub  
  42.                 String username = MainActivity.this.etUsername.getText()  
  43.                         .toString().trim();  
  44.                 String password = MainActivity.this.etPassword.getText()  
  45.                         .toString().trim();  
  46.                 if ("".equals(username)) {  
  47.                     Toast.makeText(MainActivity.this"请填写用户名",  
  48.                             Toast.LENGTH_SHORT).show();  
  49.                     return;  
  50.                 }  
  51.                 if ("".equals(password)) {  
  52.                     Toast.makeText(MainActivity.this"请填写密码",  
  53.                             Toast.LENGTH_SHORT).show();  
  54.                     return;  
  55.                 }  
  56.                 //如果已经填写了用户名和密码,执行登录操作  
  57.                 executeLogin(username, password);  
  58.             }  
  59.         });  
  60.   
  61.     }  
  62.   
  63.     private void executeLogin(String username, String password) {  
  64.         new LoginTask().execute(username, password);  
  65.     }  
  66.   
  67.     private void onLoginComplete(Integer userId) {  
  68.         if (userId == null || userId == 0) {//如果没有获取到用户ID,说明登录失败  
  69.             Toast.makeText(MainActivity.this"用户名或密码错误", Toast.LENGTH_SHORT)  
  70.                     .show();  
  71.             if (vsProgress != null) {  
  72.                 vsProgress.setVisibility(View.INVISIBLE);  
  73.             }  
  74.             return;  
  75.         }  
  76.         if (vsProgress != null) {  
  77.             vsProgress.setVisibility(View.INVISIBLE);  
  78.         }  
  79.         //如果成功获取到返回的用户ID,说明登录成功,跳转到HelloActivity  
  80.         Toast.makeText(MainActivity.this"登陆成功", Toast.LENGTH_SHORT).show();  
  81.         HelloActivity.actionStart(MainActivity.this, userId, etUsername  
  82.                 .getText().toString());  
  83.     }  
  84.   
  85.     private class LoginTask extends AsyncTask<String, Void, Integer> {  
  86.   
  87.         @Override  
  88.         protected void onPreExecute() {  
  89.             // TODO Auto-generated method stub  
  90.             super.onPreExecute();  
  91.             //进行登录验证时,显示登录进度条  
  92.             if (vsProgress == null) {  
  93.                 ViewStub vs = (ViewStub) findViewById(R.id.vsProgress);  
  94.                 vsProgress = (ViewGroup) vs.inflate();  
  95.             } else {  
  96.                 vsProgress.setVisibility(View.VISIBLE);  
  97.             }  
  98.         }  
  99.   
  100.         @Override  
  101.         protected Integer doInBackground(String... params) {  
  102.             // TODO Auto-generated method stub  
  103.             Integer result = null;  
  104.             JSONArray reqValue;  
  105.             try {  
  106.                 //将用户名和密码封装到JSONArray中,进行HTTP通信  
  107.                 reqValue = new JSONArray().put(new JSONObject().put("username",  
  108.                         params[0]).put("password", params[1]));  
  109.                 JSONArray rec = WebUtil.getJSONArrayByWeb(Config.METHOD_LOGIN,  
  110.                         reqValue);  
  111.                 if (rec != null) {//如果成功获取用户ID  
  112.                     result = rec.getJSONObject(0).getInt("userId");  
  113.                 }  
  114.             } catch (JSONException e) {  
  115.                 // TODO Auto-generated catch block  
  116.                 e.printStackTrace();  
  117.             }  
  118.             return result;  
  119.         }  
  120.   
  121.         @Override  
  122.         protected void onPostExecute(Integer result) {  
  123.             // TODO Auto-generated method stub  
  124.             super.onPostExecute(result);  
  125.             //回调  
  126.             onLoginComplete(result);  
  127.         }  
  128.   
  129.     }  
  130. }  


具体的其它相关类请下载下面的源码查看。记住一定不要忘了在AndroidManifest.xml文件中添加访问网络的权限:

[html]  view plain  copy
  1. <uses-permission android:name="android.permission.INTERNET" />  

好了,自己写写体验一下吧。代码不太符合架构规范,旨在展示Android与Web服务器的Json数据交互过程。写的不好还望各位大神指教。

源码免费下载:

源码下载

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值