android用戶端和網站資料互動的實現(基於Http協議擷取資料方法)

來源:互聯網
上載者:User

android用戶端和網站資料互動的實現(基於Http協議擷取資料方法)

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檔案中敲下:


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

org.apache.struts2.dispatcher.FilterDispatcher



struts2
/*



index.jsp


然後編寫struts.xml檔案,並放在WebRoot/WEB-INF/lib目錄下:如下代碼:


"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">














配置好後,我們再根據標籤內容來編寫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

運行成功。<喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+CjxzdHJvbmc+v827p7bLo7o8L3N0cm9uZz48L3A+CjxwPgrV4sDv0OjSqtei0uK1xMrHxKPE4sb3sNHX1Ly6tbGzycHLbG9jYWxob3N0LNLUvLAxMjcuMC4wLjHBy6Os0vK0y8jnufu7+dPasb612LXEd2Viz+7Ev7LiytS1xLuwo6yx2NDr0N64xElQzqqjujEwLjAuMi4yPC9wPgoKPGltZyBzcmM9"http://www.bkjia.com/uploads/allimg/140803/0415345363-1.gif" alt="複製代碼">

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();
}
}
}=================================================================================================================================

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.