Android客户端与服务器交互方式(1)

Android客户端与服务器交互方式(1)

Android客户端与服务器端的数据交互有多种,最常见的就是webservice和json。

为了与服务器端交互主要通过通信协议,常用的就是Http和TCP。Http基于TCP,TCP协议对应传输层,Http协议对应应用层。当客户端需要从服务器获取数据的时候,会发出一次Http请求。Http会通过TCP建立起一个到服务器的连接通道,当本次请求需要的数据完毕后,Http会立即将TCP连接断开。

而xmlrpc,ssh的json就是这两种协议扩展来的。
使用webservices传输XML文件比较简单及通用,如果对数据大小及传输速度有要求的话就用json更合适。

此次讲的就是通过json进行数据交互。

所谓的通过json进行数据交互其实就是在客户端将数据转换为json字符串发送给服务器,服务器接送到后将json转换会原数据进行处理。那么客户端怎么发送json呢,即通过Http协议的Post或Get方法。

废话不多说上代码
1. android端
2.

package com.example.helloworld;


public class MainActivity extends ActionBarActivity {

    private String responseMsg = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                //Intent intent = new Intent(MainActivity.this, InfoActivity.class);
                //startActivity(intent);
                Thread loginThread = new Thread(new LoginThread());
                loginThread.start();
            }
        });

    }

    public HttpClient getHttpClient(){
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 5*1000);
        HttpConnectionParams.setSoTimeout(httpParams, 10*1000);
        HttpClient client = new DefaultHttpClient(httpParams);
        return client;
    }

    private void sendJson(){
        //boolean loginValidate = false;
        String urlStr = "http://192.168.1.24:8080/servletTest/test";
        HttpPost post = new HttpPost(urlStr);
        try{
            //向服务器写json
            JSONObject json1 = new JSONObject();
            //Object email = null;
            Object email = "hlelo";
            json1.put("email", email);
            //Object pwd = null;
            Object pwd = "wodls";
            json1.put("password", pwd);

            System.out.println("=============="+json.toString());
            //保证json数据不是乱码
            StringEntity se = new StringEntity(json.toString());
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(se);

            //发送json给服务器
            HttpClient httpClient = getHttpClient();
            HttpResponse httpResponse = httpClient.execute(post);

            /*int httpCode = httpResponse.getStatusLine().getStatusCode();
            if(httpCode == HttpURLConnection.HTTP_OK && httpResponse != null){
                //org.apache.http.Header[] headers = httpResponse.getAllHeaders();
                HttpEntity entity = httpResponse.getEntity();
                //org.apache.http.Header header = httpResponse.getFirstHeader("content-type");
                //读取服务器返回的json
                InputStream inputStream = entity.getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String s;
                while((s= reader.readLine())!= null){
                    result.append(s);
                }
                reader.close();

                JSONObject jsonObject = new JSONObject(result.toString());
                String nameString = jsonObject.getString("email");
                String passString = jsonObject.getString("password");
                System.out.println("===============email is: "+nameString+", password is: "+passString);*/
        }catch(Exception exception){
            exception.printStackTrace();
        }
    }

    class LoginThread implements Runnable{
        public void run(){           
            sendJson();
        }
    }    
 }

2.servlet端

package cn.dragon.servlet;


public class ServletDemoFirst extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //处理json内容
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json");
        String acceptjson = "";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream(), "utf-8"));
            StringBuffer sb = new StringBuffer("");
            String temp;
            while((temp = br.readLine()) != null){
                sb.append(temp);
            }
            br.close();                     
        //以上的过程都从request中读取json,并将json转换成string,这样可以显示出来。最终String类型的json就是acceptjson  
            acceptjson = sb.toString();
            System.out.println("=======json is==========="+acceptjson);
            if(acceptjson != ""){
                //System.out.println("get the json successfully");
                JSONObject jo = JSONObject.fromObject(acceptjson);
          //email即是android端发送过来的json当中的一个key,我们使用get方法读取对应的value
                System.out.println(jo.get("email"));
            }
            else{
                System.out.println("get the json failed");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

}

参考出处:1.http://blog.csdn.net/panfb227
2.http://www.cnblogs.com/zhawj159753/p/3949956.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值