android客户端一般不直接访问网站数据库,而是像浏览器一样发送get或者post请求,然后网站返回客户端能理解的数据格式,客户端解析这些数据,显示在界面上,常用的数据格式是xml和json。
可以理解客户端其实是一个你自己定义标记语言的浏览器,一般浏览器能解析的是html+css的数据,而android客户端能解析的是xml和json(或者都不是而是你自己定义的火星格式),服务端为了能满足客户端输出这种数据格式的需求,不得不专门针对客户端开发不同于浏览器访问的接口。
开发一个网站的客户端你需要:
1.在客户端模拟get和post请求,请求最终还是通过http协议以url的形式发送
2.在客户单解析服务器返回的数据
3.在服务端根据请求生成相应的json数据(强烈建议使用json而不是xml,相同字符的json能返回更多的有用数据而且解析方便速度快)
java本身的HttpURLConnection类完全可以实现get和post,但是非常麻烦,我们还是使用HttpClient这个开源代码来实现。
本人总结了android与服务器之间的交互有两种方式
1.http协议(一般我们都用HttpClient这个开源的项目)基于Http协议获取数据方法。
那我们采取的服务器端技术为java,框架为Struts2,或者可以有Servlet,又或者可直接从JSP页面中获取数据。
那么,接下来我们便开始这一路程:
首先:编写服务器端方法,我这里采用的MVC框架是Struts2,目的很单纯,就是为了以后做个完整的商业项目,技术配备为:android+SSH。当然,篇幅有限,我这里就直接用Strtus2而已。
服务器端:
为了给项目添加Struts2的支持,我们必须导入Struts2的一些类库,如下即可(有些jar包是不必的,但是我们后来扩展可能是要使用到的,就先弄进去):
1: xwork-core-2.2.1.1.jar
2: struts2-core-2.2.1.1.jar
3: commons-logging-1.0.4.jar
4: freemarker-2.3.16.jar
5: ognl-3.0.jar
6: javassist-3.7.ga.jar
7:commons-ileupload.jar
8:commons-io.jar
9:json-lib-2.1-jdk15.jar 处理JSON格式数据要使用到
10:struts2-json-plugin-2.2.1.1.jar 基于struts2的json插件
以上的jar包,需要放在WebRoot/WEB-INF/lib目录下
然后在web.xml文件中敲下:
<? xml version="1.0" encoding="UTF-8" ?> < web-app version ="2.5" xmlns ="http://java.sun.com/xml/ns/javaee" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" > <!-- 定义Struts2的核心控制器:FilterDispatcher --> < filter > <!-- 定义核心Filter的名称 --> < filter-name > struts2 </ filter-name > <!-- 定义Filter的实现类 --> < filter-class > org.apache.struts2.dispatcher.FilterDispatcher </ filter-class > </ filter > < filter-mapping > < filter-name > struts2 </ filter-name > < url-pattern > /* </ url-pattern > </ filter-mapping > < welcome-file-list > < welcome-file > index.jsp </ welcome-file > </ welcome-file-list > </ web-app >然后编写struts.xml文件,并放在WebRoot/WEB-INF/lib目录下:如下代码:
<? xml version="1.0" encoding="UTF-8" ?> <! DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd" > < struts > <!-- setting encoding,DynamicMethod,language <constant name="struts.custom.i18n.resources" value="messageResource"></constant> --> < constant name ="struts.i18n.encoding" value ="UTF-8" ></ constant > < constant name ="struts.enable.DynamicMethodInvocation" value ="true" ></ constant > <!-- add package here extends="struts-default" --> < package name ="dongzi" extends ="json-default" > <!-- 需要将struts-default改为json-default --> <!-- setting action --> < action name ="login" class ="com.dongzi.action.loginAction" method ="login" > < result type ="json" ></ result > <!-- 返回值类型设置为json,不设置返回页面 --> </ action > </ package > </ struts >配置好后,我们再根据<action>标签内容来编写action。方法为method对应的login,类名为loginAction,
注意:包继承为:json-default ,输出结果类型为json
如下: public class loginAction extends ActionSupport implements ServletRequestAware,ServletResponseAware { /** * */ private static final long serialVersionUID = 1L ; HttpServletRequest request; HttpServletResponse response; public void setServletRequest(HttpServletRequest request) { this .request = request; } public void setServletResponse(HttpServletResponse response) { this .response = response; } public void login(){ try { // HttpServletRequest request =ServletActionContext.getRequest(); // HttpServletResponse response=ServletActionContext.getResponse(); this .response.setContentType( " text/html;charset=utf-8 " ); this .response.setCharacterEncoding( " UTF-8 " ); if ( this .request.getParameter( " username " ).equals( " 123456 " )){ this .response.getWriter().write( " 真的很奇怪,日本人! " ); } else if ( this .request.getParameter( " username " ).equals( " zhd " )){ this .response.getWriter().write( " 没有错,我就是东子哥! " ); } else { this .response.getWriter().write( " 我就是东子哥! " ); } // 将要返回的实体对象进行json处理 // JSONObject json=JSONObject.fromObject(this.getUsername()); // 输出格式如:{"id":1, "username":"zhangsan", "pwd":"123"} // System.out.println(json); // this.response.getWriter().write(json.toString()); /** JSONObject json=new JSONObject(); json.put("login", "login"); response.setContentType("text/html;charset=utf-8"); System.out.println(json); byte[] jsonBytes = json.toString().getBytes("utf-8"); response.setContentLength(jsonBytes.length); response.getOutputStream().write(jsonBytes); * */ /** JSONObject json=new JSONObject(); json.put("login", "login"); byte[] jsonBytes = json.toString().getBytes("utf-8"); response.setContentType("text/html;charset=utf-8"); response.setContentLength(jsonBytes.length); response.getOutputStream().write(jsonBytes); response.getOutputStream().flush(); response.getOutputStream().close(); * */ } catch (Exception e) { e.printStackTrace(); } // return null; }}运行查看下:http://localhost:8080/PDAServer/login.action?username=123456 当然你可以输入其他参数的URL
运行成功。
客户端:
这里需要注意的是模拟器把自己当成了localhost,以及127.0.0.1了,因此如果基于本地的web项目测试的话,必须修改IP为:10.0.2.2
public class MainActivity extends Activity { /** Called when the activity is first created. */ // 模拟器自己把自己当成localhost了,服务器应该为10.0.2.2 private static String url = " http://10.0.2.2:8080/PDAServer/login.action " ; @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); getPDAServerData(url); } /** * 请求服务 * @param url */ private void getPDAServerData(String url){ url += " ?username=123456 " ; HttpClient client = new DefaultHttpClient(); HttpPost request; try { request = new HttpPost( new URI(url)); HttpResponse response = client.execute(request); // 判断请求是否成功 if (response.getStatusLine().getStatusCode() == 200 ){ HttpEntity entity = response.getEntity(); if (entity != null ){ String out = EntityUtils.toString(entity); new AlertDialog.Builder( this ).setMessage(out).create().show(); } } } catch (URISyntaxException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } =================================================================================================================================转载于:https://www.cnblogs.com/dandre/p/4507044.html
相关资源:C#中客户端通过http协议访问服务端