androidclient和站点数据交互的实现(基于Http协议获取数据方法)

出门莫恨无人随,书中车马多如簇。这篇文章主要讲述androidclient和站点数据交互的实现(基于Http协议获取数据方法)相关的知识,希望能为你提供帮助。
        androidclient一般不直接訪问站点数据库,而是像浏览器一样发送get或者post请求。然后站点返回client能理解的数据格式,client解析这些数据。显示在界面上。经常使用的数据格式是xml和json。
能够理解client事实上是一个你自定义标记语言的浏览器,一般浏览器能解析的是html+css的数据,而androidclient能解析的是xml和json(或者都不是而是你自定义的火星格式),服务端为了能满足client输出这样的数据格式的需求,不得不专门针对client开发不同于浏览器訪问的接口。
    开发一个站点的client你须要:
1.在client模拟get和post请求。请求终于还是通过http协议以url的形式发送
2.在客户单解析server返回的数据
3.在服务端依据请求生成对应的json数据(强烈建议使用json而不是xml。同样字符的json能返回很多其它的实用数据并且解析方便速度快)
java本身的HttpURLConnection类全然能够实现get和post,可是很麻烦。我们还是使用HttpClient这个开源码来实现。


本人总结了android与server之间的交互有两种方式
1.http协议(一般我们都用HttpClient这个开源的项目)基于Http协议获取数据方法。
      那我们採取的server端技术为java,框架为Struts2,或者能够有Servlet,又或者可直接从JSP页面中获取数据。
那么,接下来我们便開始这一路程:
首先:编写server端方法,我这里採用的MVC框架是Struts2。目的非常单纯,就是为了以后做个完整的商业项目。技术配备为:android+SSH。当然,篇幅有限。我这里就直接用Strtus2而已。

server端:
为了给项目加入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文件里敲下:

androidclient和站点数据交互的实现(基于Http协议获取数据方法)

文章图片
androidclient和站点数据交互的实现(基于Http协议获取数据方法)

文章图片
< ?
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>

androidclient和站点数据交互的实现(基于Http协议获取数据方法)

文章图片

然后编写struts.xml文件,并放在WebRoot/WEB-INF/lib文件夹下:例如以下代码:

   

androidclient和站点数据交互的实现(基于Http协议获取数据方法)

文章图片
androidclient和站点数据交互的实现(基于Http协议获取数据方法)

文章图片
< ?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="https://www.songbingjia.com/android/messageResource"> < /constant>
-->
< constant name="struts.i18n.encoding" value="https://www.songbingjia.com/android/UTF-8"> < /constant>
< constant name="struts.enable.DynamicMethodInvocation" value="https://www.songbingjia.com/android/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>

androidclient和站点数据交互的实现(基于Http协议获取数据方法)

文章图片
配置好后,我们再依据< action> 标签内容来编写action。
方法为method相应的login。类名为loginAction,
?注意:包继承为:json-default 。输出结果类型为json
例如以下:
androidclient和站点数据交互的实现(基于Http协议获取数据方法)

文章图片
androidclient和站点数据交互的实现(基于Http协议获取数据方法)

文章图片
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 voidlogin(){
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;
}
}

androidclient和站点数据交互的实现(基于Http协议获取数据方法)

文章图片
  执行查看下:http://localhost:8080/PDAServer/login.action?username=123456  当然你能够输入其它參数的URL
androidclient和站点数据交互的实现(基于Http协议获取数据方法)

文章图片

执行成功。
client:
【androidclient和站点数据交互的实现(基于Http协议获取数据方法)】这里须要注意的是模拟器把自己当成了localhost,以及127.0.0.1了,因此假设基于本地的web项目測试的话。必须改动IP为:10.0.2.2
androidclient和站点数据交互的实现(基于Http协议获取数据方法)

文章图片
public class MainActivity extends Activity {
/** Called when the activity is first created. */
//模拟器自己把自己当成localhost了,server应该为10.0.2.2
private staticString 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){
HttpEntityentity=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();
}
}
}=================================================================================================================================


    推荐阅读