androidclient和站点数据交互的实现(基于Http协议获取数据方法)
? ? ? ?androidclient一般不直接訪問站點(diǎn)數(shù)據(jù)庫(kù),而是像瀏覽器一樣發(fā)送get或者post請(qǐng)求。然后站點(diǎn)返回client能理解的數(shù)據(jù)格式,client解析這些數(shù)據(jù)。顯示在界面上。經(jīng)常使用的數(shù)據(jù)格式是xml和json。
能夠理解client事實(shí)上是一個(gè)你自定義標(biāo)記語(yǔ)言的瀏覽器,一般瀏覽器能解析的是html+css的數(shù)據(jù),而androidclient能解析的是xml和json(或者都不是而是你自定義的火星格式),服務(wù)端為了能滿足client輸出這樣的數(shù)據(jù)格式的需求,不得不專門針對(duì)client開發(fā)不同于瀏覽器訪問的接口。
??開發(fā)一個(gè)站點(diǎn)的client你須要:
1.在client模擬get和post請(qǐng)求。請(qǐng)求終于還是通過http協(xié)議以u(píng)rl的形式發(fā)送
2.在客戶單解析server返回的數(shù)據(jù)
3.在服務(wù)端依據(jù)請(qǐng)求生成對(duì)應(yīng)的json數(shù)據(jù)(強(qiáng)烈建議使用json而不是xml。同樣字符的json能返回很多其它的實(shí)用數(shù)據(jù)并且解析方便速度快)
java本身的HttpURLConnection類全然能夠?qū)崿F(xiàn)get和post,可是很麻煩。我們還是使用HttpClient這個(gè)開源碼來實(shí)現(xiàn)。
本人總結(jié)了android與server之間的交互有兩種方式
1.http協(xié)議(一般我們都用HttpClient這個(gè)開源的項(xiàng)目)基于Http協(xié)議獲取數(shù)據(jù)方法。
? ? ?那我們採(cǎi)取的server端技術(shù)為java,框架為Struts2,或者能夠有Servlet,又或者可直接從JSP頁(yè)面中獲取數(shù)據(jù)。
那么,接下來我們便開始這一路程:
首先:編寫server端方法,我這里採(cǎi)用的MVC框架是Struts2。目的非常單純,就是為了以后做個(gè)完整的商業(yè)項(xiàng)目。技術(shù)配備為:android+SSH。當(dāng)然,篇幅有限。我這里就直接用Strtus2而已。
server端:
為了給項(xiàng)目加入Struts2的支持,我們必須導(dǎo)入Struts2的一些類庫(kù),例如以下就可以(有些jar包是不必的。可是我們后來擴(kuò)展可能是要使用到的。就先弄進(jìn)去):
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格式數(shù)據(jù)要使用到
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的實(shí)現(xiàn)類 -->
<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> <!--返回值類型設(shè)置為json,不設(shè)置返回頁(yè)面-->
</action>
</package>
</struts>
配置好后,我們?cè)僖罁?jù)<action>標(biāo)簽內(nèi)容來編寫action。
方法為method相應(yīng)的login。類名為loginAction,
注意:包繼承為:json-default 。輸出結(jié)果類型為json
例如以下: public class loginAction extends ActionSupport implementsServletRequestAware,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("沒有錯(cuò),我就是東子哥!");
}else{
this.response.getWriter().write("我就是東子哥!");
}
//將要返回的實(shí)體對(duì)象進(jìn)行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;
}
}
?執(zhí)行查看下:http://localhost:8080/PDAServer/login.action?username=123456? 當(dāng)然你能夠輸入其它參數(shù)的URL
執(zhí)行成功。
client:
這里須要注意的是模擬器把自己當(dāng)成了localhost,以及127.0.0.1了,因此假設(shè)基于本地的web項(xiàng)目測(cè)試的話。必須改動(dòng)IP為:10.0.2.2
public class MainActivity extends Activity {/** Called when the activity is first created. */
//模擬器自己把自己當(dāng)成localhost了,server應(yīng)該為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);
}
/**
* 請(qǐng)求服務(wù)
* @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);
//推斷請(qǐng)求是否成功
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();
}
}
} =================================================================================================================================
轉(zhuǎn)載于:https://www.cnblogs.com/cxchanpin/p/7019584.html
總結(jié)
以上是生活随笔為你收集整理的androidclient和站点数据交互的实现(基于Http协议获取数据方法)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#中的深复制和浅复制(在C#中克隆对象
- 下一篇: 使用字体图标