Android客戶端與服務端之間傳遞json數據

服務端:mysql+hibernate;
客戶端:androidjava

最近本身在作聊天軟件的時候要在服務端和客戶端之間進行數據傳遞,開始得時候使用socket,後來發現使用socket有點侷限性,因此改用了http的方式,摸索了兩天,終於連通了服務端和客戶端mysql

思路:android

1.服務端提供接收數據的servlet
2.客戶端將須要發送的數據轉換成json格式
3.客戶端啓動線程,將json數據放入request請求中,經過httpclient發送至服務端
4.服務端經過request拿到輸入流,解析爲json數據
5.服務端進行業務邏輯處理(若無需進行進行業務邏輯處理,此步驟可省略)
6.將須要返回的數據或業務邏輯處理結果轉換成json格式,經過response的流將json數據輸出給客戶端
7.客戶端經過response獲取流,解析成json數據
8.若須要更新UI,則經過handler將數據發送回主線程,更新UIsql

服務端代碼:apache

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.durian.fc.server.servlet;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.durian.fc.server.entity.User;
import com.durian.fc.server.service.UserManager;
import net.sf.json.JSONObject;

public class RegisterServlet extends HttpServlet {
        private static final long serialVersionUID = 541282327938079229L;
        private UserManager manager = new UserManager();

    @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                        throws ServletException, IOException {
            doPost(req, resp);
        }

    @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                        throws ServletException, IOException {
        StringBuilder sb = new StringBuilder();
        String s = null;
           BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
            while((s=br.readLine())!=null){
                sb.append(s);
            }
            JSONObject jo= JSONObject.fromObject(sb.toString());
            String password = jo.getString("password");
            String phone = jo.getString("phone");
            System.out.println(s);
            Boolean b = false;
            b = manager.saveUser(password,phone);
            jo.clear();
            jo.put("isExit", b);
            PrintWriter pw = resp.getWriter();
            pw.write(jo.toString());
        }
}

客戶端工具類代碼:json

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.durian.fc.client.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONObject;
import android.util.Log;

public class HttpUtils {
    public final static int METHOD_GET = 1;
    public final static int METHOD_POST = 2;

    public static HttpEntity getHttpEntity(String uri,int method,JSONObject json){
        HttpEntity entity = null;
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,10000);
        HttpUriRequest req = null;
        switch (method) {
        case METHOD_GET:
            req = new HttpGet(uri);
            break;
        case METHOD_POST:
            try {
                Log.i("info", "post started");
                req = new HttpPost(uri);
                ((HttpPost)req).setEntity(new StringEntity(json.toString()));
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            break;
        }
        try {
            HttpResponse res = client.execute(req);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                return entity =  res.getEntity();
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return entity;
    }

    public static InputStream getInputStream(HttpEntity entity){
        InputStream in = null;
        try {
            if(entity!= null){
                return in = entity.getContent();
            }
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return in;
    }

客戶端代碼app

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
jo.put("password", pass1);
                        new Thread(new Runnable() {
                            public void run() {
                                HttpEntity entity = HttpUtils.getHttpEntity("http://192.168.1.105:8080/FCS2/registerServlet", 2, jo);
                                InputStream in = HttpUtils.getInputStream(entity);
                                if(in!=null){
                                    try {
                                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                                        StringBuilder sb = new StringBuilder();
                                        String s = null;
                                        while((s=br.readLine())!=null){
                                            sb.append(s);
                                        }
                                        JSONObject jo2 = new JSONObject(sb.toString());
                                        System.out.println(jo2.getBoolean("isExit"));
                                        Message msg = Message.obtain(handler, 1, jo2.getBoolean("isExit"));
                                        msg.sendToTarget();
                                    } catch (Exception e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }).start();
相關文章
相關標籤/搜索