Android客户端和Servlet服务器端通过JSON交互
本文结构如下:
1. android和servlet之间的直接信息传递(不通过json)
1.1 android端代码
1.2 servlet端代码
2. android和servlet之间通过json进行交互
2.1 android端代码
2.2 servlet端代码
=============================================================
1. android和servlet之间的直接信息传递
在android端通过httpclient去访问服务器,发送request请求,并获取response。
在servlet端只需要简单的定义doGet方法和doPost方法即可。
1.1 android端代码
package com.example.helloworld; public class MainActivity extends ActionBarActivity { private String responseMsg = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button1 = (Button)findViewById(R.id.button1); button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Thread loginThread = new Thread(new LoginThread()); loginThread.start(); } }); }
//发送请求的主要方法 private boolean loginServer(){ boolean loginValidate = false;
//servlet服务器地址是 String urlStr = "http://192.168.1.24:8080/servletTest/test"; HttpPost request = new HttpPost(urlStr); try { HttpClient client = getHttpClient(); //执行请求 HttpResponse response = client.execute(request);
//response是servlet给出的返回结果 if(response.getStatusLine().getStatusCode() == 200){ loginValidate = true; responseMsg = EntityUtils.toString(response.getEntity()); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return loginValidate; } public HttpClient getHttpClient(){ BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5*1000); HttpConnectionParams.setSoTimeout(httpParams, 10*1000); HttpClient client = new DefaultHttpClient(httpParams); return client; } class LoginThread implements Runnable{ public void run(){ boolean loginValidate = loginServer(); System.out.println("======================bool is :"+loginValidate+"----------------response: "+responseMsg); } } }
1.2 servlet端代码
package cn.dragon.servlet; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.sun.corba.se.pept.transport.Connection; public class ServletDemoFirst extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ // response.setContentType("text/html; charset=GB2312"); // PrintWriter outPrintWriter = response.getWriter(); // outPrintWriter.println("hello"); // outPrintWriter.close(); //Connection conn = null;
//首先建立数据库连接 String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "admin"; PrintWriter out = response.getWriter(); //out.println("welcom"); try { Class.forName(driver); java.sql.Connection conn = DriverManager.getConnection(url, user, password); //out.println("loading success"); Statement statement = conn.createStatement();
//进行数据库查询。 ResultSet rs = statement.executeQuery("select * from career"); ArrayList<String> list1 = new ArrayList<String>(); while(rs.next()){ //out.println(rs.getString(1)); list1.add(rs.getString(1)); }
//out用来向客户端返回数据。如果用网页访问这个网址,查询数据库的结果就显示在网页上,如果用android访问,就返回给android手机 out.println(list1.toString()); rs.close(); statement.close(); conn.close(); } catch (ClassNotFoundException cnfex) { //System.err.println("装载 JDBC/ODBC 驱动程序失败。"); out.println("loading JDBC failed"); cnfex.printStackTrace(); System.exit(1); // terminate program } catch (SQLException sqlex) { //System.err.println("无法连接数据库"); out.println("can not connect to the database"); sqlex.printStackTrace(); System.exit(1); // terminate program } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
doGet(request, response); } }
以上就是两部分的代码。都比较好理解,而且也给了一些注释。
==================================================================
2. 通过JSON进行客户端服务器的通讯
2.1 android端
package com.example.helloworld; public class MainActivity extends ActionBarActivity { private String responseMsg = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button1 = (Button)findViewById(R.id.button1); button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub //Intent intent = new Intent(MainActivity.this, InfoActivity.class); //startActivity(intent); Thread loginThread = new Thread(new LoginThread()); loginThread.start(); } }); } public HttpClient getHttpClient(){ BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5*1000); HttpConnectionParams.setSoTimeout(httpParams, 10*1000); HttpClient client = new DefaultHttpClient(httpParams); return client; } private void sendJson(){ //boolean loginValidate = false; String urlStr = "http://192.168.1.24:8080/servletTest/test"; HttpPost post = new HttpPost(urlStr); try{ //向服务器写json JSONObject json1 = new JSONObject(); //Object email = null; Object email = "hlelo"; json1.put("email", email); //Object pwd = null; Object pwd = "wodls"; json1.put("password", pwd); System.out.println("=============="+json.toString()); //保证json数据不是乱码 StringEntity se = new StringEntity(json.toString()); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); //发送json给服务器 HttpClient httpClient = getHttpClient(); HttpResponse httpResponse = httpClient.execute(post); /*int httpCode = httpResponse.getStatusLine().getStatusCode(); if(httpCode == HttpURLConnection.HTTP_OK && httpResponse != null){ //org.apache.http.Header[] headers = httpResponse.getAllHeaders(); HttpEntity entity = httpResponse.getEntity(); //org.apache.http.Header header = httpResponse.getFirstHeader("content-type"); //读取服务器返回的json InputStream inputStream = entity.getContent(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader reader = new BufferedReader(inputStreamReader); String s; while((s= reader.readLine())!= null){ result.append(s); } reader.close(); JSONObject jsonObject = new JSONObject(result.toString()); String nameString = jsonObject.getString("email"); String passString = jsonObject.getString("password"); System.out.println("===============email is: "+nameString+", password is: "+passString);*/ }catch(Exception exception){ exception.printStackTrace(); } } class LoginThread implements Runnable{ public void run(){ sendJson(); } } }
2.2 servlet端代码
package cn.dragon.servlet; public class ServletDemoFirst extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ //处理json内容 response.setCharacterEncoding("UTF-8"); response.setContentType("text/json"); String acceptjson = ""; try { BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream(), "utf-8")); StringBuffer sb = new StringBuffer(""); String temp; while((temp = br.readLine()) != null){ sb.append(temp); } br.close();
//以上的过程都从request中读取json,并将json转换成string,这样可以显示出来。最终String类型的json就是acceptjson acceptjson = sb.toString(); System.out.println("=======json is==========="+acceptjson); if(acceptjson != ""){ //System.out.println("get the json successfully"); JSONObject jo = JSONObject.fromObject(acceptjson);
//email即是android端发送过来的json当中的一个key,我们使用get方法读取对应的value System.out.println(jo.get("email")); } else{ System.out.println("get the json failed"); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
其实应该还有一段内容是servlet将json返还给android端,然后android端再解析出来。关于android端的解析过程在注释掉的部分中,但这段内容我还没有验证。
下面稍微补充一点关于JSONArray的内容——JSONArray如何传输与解析
/**** android: sendJson() *****/ private void sendJson(){ //boolean loginValidate = false; StringBuilder result = new StringBuilder(); String urlStr = "http://192.168.1.24:8080/servletTest/test"; HttpPost post = new HttpPost(urlStr); List<NameValuePair> params = new ArrayList<NameValuePair>(); //params.add(new BasicNameValuePair("name", "this is post")); try{ //向服务器写json JSONObject json1 = new JSONObject(); //Object email = null; Object email = "hlelo"; json1.put("email", email); //Object pwd = null; Object pwd = "wodls"; json1.put("password", pwd); JSONArray jsonArray = new JSONArray();
//生成一个JSONARRAY并将上面的json装入其中 jsonArray.put(0, json1); JSONObject json = new JSONObject();
//再生成一个JSONObject,将刚才的JSONArray放入其中,再发送到服务器端 json.put("dao", jsonArray); System.out.println("=============="+json.toString()); //保证json数据不是乱码 StringEntity se = new StringEntity(json.toString()); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); //发送json给服务器 HttpClient httpClient = getHttpClient(); HttpResponse httpResponse = httpClient.execute(post); }catch(Exception exception){ exception.printStackTrace(); }
/***** servlet: doPost() *****/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{//处理json内容 System.out.println("=======json is==========="); response.setCharacterEncoding("UTF-8"); response.setContentType("text/json"); String acceptjson = ""; try { BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream(), "utf-8")); StringBuffer sb = new StringBuffer(""); String temp; while((temp = br.readLine()) != null){ sb.append(temp); } br.close(); acceptjson = sb.toString(); System.out.println("=======json is==========="+acceptjson); if(acceptjson != ""){ //System.out.println("get the json successfully");
//先获取json
JSONObject jo = JSONObject.fromObject(acceptjson); //再获取json中包含的jsonarry,dao是刚才android端给出的key JSONArray ja = jo.getJSONArray("dao");
//循环获取jsonarray中的每个json for(int i = 0; i < ja.size(); i++){ JSONObject object = JSONObject.fromObject(ja.get(i));
//获取json中的email值,email是json中的key
System.out.println("email is: "+object.get("email")); } } else{ System.out.println("get the json failed"); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
Bon Appetite~
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。