1. 程式人生 > >實現Android客戶端與Eclipse伺服器端基於Okthhp簡單通訊

實現Android客戶端與Eclipse伺服器端基於Okthhp簡單通訊

最近在重溫知識,所以藉此機會也想把自己寫的一些心得寫出來供大家分享,寫的有誤或者不好的地方望大家見諒,好了,廢話少說,直接進入正題,下面給大家介紹的就是基於目前主流網路通訊框架的okhttp實現的Android與Eclipse通訊。

首先說明:我用的Android客戶端是Android studio,現在基本上都是用AS來開發App的,我們也要跟上主流是吧,Eclipse伺服器端我是用Tomcat來實現的,簡單輕巧,其實開發javaweb專案時,用MyEclipse是最合適的,但是這個正版需要money,學生黨表示很無奈,好了,環境介紹完了,下面就是純程式碼了。

先從Eclipse伺服器端說起吧,我這兒用的是servlet實現的,主要就是把核心程式碼doPost()方法給貼出來了

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");//解決中文亂碼
response.setHeader("content-type","text/html;charset=UTF-8");//解決中文亂碼
PrintWriter out = response.getWriter();

Student student1 = new Student();
student1.setName("程建新");  
student1.setAge(21);
student1.setBirthday("1996-09-08");
String[] str = {"讀書", "運動"};
student1.setHobby(str);

Gson gson = new Gson();
out.print(gson.toJson(student1));//列印Json資料
}

現在網路之間通訊主流是用Json或xml通訊,攜帶資料量較大,便於傳輸

下面是Android studio客戶端的核心程式碼

private void getInformation() {
        String url = "http://localhost:8080/StudentServlet/Stu";//伺服器地址
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        call.enqueue(
new Callback() {//okHttp非同步載入 @Override public void onFailure(Request request, IOException e) { Log.d("伺服器連線", "連線失敗!!!"); } @Override public void onResponse(Response response) throws IOException { // String str = response.body().string(); //注意這裡用的是string()方法,而不能用toString()方法,兩者是有區別的// // Gson gson = new Gson(); // Student stu = gson.fromJson(str, Student.class); InputStream input = response.body().byteStream();//用InputStream輸入流接收資料 BufferedInputStream bufinput = new BufferedInputStream(input); byte[] buffer = new byte[10000]; int bytes = bufinput.read(buffer); final String str = new String(buffer, 0, bytes); Log.d("伺服器連線", "連線成功!"); Message message = Message.obtain(); message.what = 1; Bundle bundle = new Bundle(); bundle.putString("Name", str); message.setData(bundle); handler.sendMessage(message);//View控制元件必須在主執行緒中更新 });
private Handler handler = new Handler(){//接受Message資訊,執行相應動作
    @Override
public void handleMessage(Message msg) {
        switch (msg.what){
            case 1:
                Bundle bundle = msg.getData();
                textView.setText(bundle.getString("Name", "NULL"));
                break;
        }
    }
};