Android後端伺服器的搭建

來源:互聯網
上載者:User

標籤:

  一直做Android前端,今天突然心血來潮想搭建一個後台玩玩。平時都是需要什麼樣的介面直接出個介面文檔扔給背景兄弟,自己從來不操心他們內部的實現問題。今天懷著好奇的心理去搭建了一個JAVA編譯環境下的後台伺服器。聽說用PHP搭建伺服器的居多,但是我們做大Android的最熟悉的還是Java了,所以下面我就開始搭建這個伺服器。很簡單。。。

  首先我下載了一個myelipse應為我們開發android的eclipse不能建立web project 要不然你去下載個外掛程式也行,下載好以後建立web project會產生一個目錄,然後右鍵你的這個項目選擇myeclipse  -> add structs capabilities... 選擇2.1 finish  OK這樣就建立成功這個項目了,下面我貼出來我的項目樹供大家參考(感謝yayun0516 ,他的博文給了我很大的協助,但是其中有些不足我已經在下面改正了)

下面配置structs.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts>    <package name="struts2" extends="struts-default" namespace="/">        <action name="getjson" class="com.shao.action.JSONAction"            method="json">            <result name="success">index.jsp</result>        </action>    </package></struts>    

只有這一個需要配置,其他的在你添加struct的時候就會自動產生。下面建立類型檔案

package com.shao.domain;public class Music {            private Integer id;          private String name;          private String time;        private String  author;        public Integer getId() {            return id;        }        public void setId(Integer id) {            this.id = id;        }        public String getName() {            return name;        }        public void setName(String name) {            this.name = name;        }        public String getTime() {            return time;        }        public void setTime(String time) {            this.time = time;        }        public String getAuthor() {            return author;        }        public void setAuthor(String author) {            this.author = author;        }     }   

然後再建立轉json的方法JSONAction:

package com.shao.action;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.interceptor.ServletRequestAware;import org.apache.struts2.interceptor.ServletResponseAware;import com.google.gson.Gson;import com.opensymphony.xwork2.ActionSupport;import com.shao.domain.Music;public class JSONAction extends ActionSupport implements ServletRequestAware,        ServletResponseAware {    /**       *        */    private static final long serialVersionUID = -3604892179657815531L;    private HttpServletRequest request;    private HttpServletResponse response;    private String format;    public String getFormat() {        return format;    }    public void setFormat(String format) {        this.format = format;    }    @Override    public void setServletRequest(HttpServletRequest request) {        this.request = request;    }    @Override    public void setServletResponse(HttpServletResponse response) {        this.response = response;    }    public void json() {        List<Music> list = new ArrayList<Music>();        Gson gson = new Gson();        Music m1 = new Music();        m1.setId(1);        m1.setAuthor("周");        m1.setName("外婆");        m1.setTime("04:04");        list.add(m1);        Music m2 = new Music();        m2.setId(2);        m2.setAuthor("周杰倫");        m2.setName("半獸人");        m2.setTime("04:05");        list.add(m2);        Music m3 = new Music();        m3.setId(3);        m3.setAuthor("周杰倫");        m3.setName("烏克麗麗");        m3.setTime("02:55");        list.add(m3);        java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Music>>() {        }.getType(); // 指定type        String beanListToJson = gson.toJson(list, type); // list轉換成json字串        System.out.println("GSON-->" + beanListToJson);        try {            response.setContentType("application/json; charset=GBK");            response.setCharacterEncoding("UTF-8");            this.response.getWriter().write(beanListToJson);        } catch (IOException e) {            e.printStackTrace();        }    }}
 response.setContentType("application/json; charset=GBK");一定要注意,如果不加這句會在你請求伺服器資料的時候,中文出現亂碼現象,同時在index.jsp中加入了contentType="text/html; charset=GBK"
還有不要忘了匯入Gson包。
完了,就這樣伺服器就完成了,下面運行一下 run as -> myeclipse service application 成功後會彈出一個框,上面寫著This is my JSP page.這就說明你已經成功建立了伺服器。
下面開啟http://localhost:8080/Test2/getjson.action 下面就是伺服器返回的內容了。


基本就是這樣了,又不懂的可以問我。下面說android端的,更簡單了。
建立我們的項目然後加入xutils和gson包。

這是一個建立的項目,在activity_main.xml中我給那個TextView添加了一個id
然後在MainActivity中實現如下:
package com.example.test2;import com.lidroid.xutils.HttpUtils;import com.lidroid.xutils.exception.HttpException;import com.lidroid.xutils.http.ResponseInfo;import com.lidroid.xutils.http.callback.RequestCallBack;import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.TextView;public class MainActivity extends ActionBarActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        final TextView text = (TextView) findViewById(R.id.text);        HttpUtils httpUtils = new HttpUtils();        httpUtils.send(HttpMethod.POST, "http://192.168.199.171:8080/Test2/getjson.action", new RequestCallBack<String>() {            public void onFailure(HttpException arg0, String arg1) {                Log.d("=====================onFailure", arg1+";"+arg0.toString());                            }            public void onSuccess(ResponseInfo<String> arg0) {                Log.d("=====================onSuccess", arg0.result);                text.setText(arg0.result);            }                            });    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}

整個android端就是這樣了,下面我們運行一下剛才的資料已經顯示在了該TextView上。

 

其實整個代碼內容是很簡單的,主要難的地方就是在環境搭建上,大家多練練吧,整個代碼是我跑下來的,所以代碼沒有問題,如果你跑不成功就多去研究研究環境搭建。

分享至此,以後可以往這方面多瞭解一下,就算不做後台開發,也要多瞭解瞭解,減少溝通成本。

 

 

Android後端伺服器的搭建

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.