ym——Android从零开始(16)(HTTP协议请求、获取图片、json数据)(新)

转载请注明本文出自Cym的博客(http://blog.csdn.net/cym492224103),谢谢支持!


前言

android应用开发必不可少的http协议通讯技术!


HTTP协议提交数据

搭建服务器环境

当下最流行的开发环境:

        Eclipse

当下最流行的J2EE框架集成体系:

        2.1 Struts2MVC

        2.2 Hibernate3ORM

        3.3 Spring FrameworkIoCAOP


Getpost提交区别

get请求的参数是带在url后面

post的参数是以请求实体的形式

get请求是不安全的,以为可以被别人看见而且服务器对url的长度做了限制,

2k 4k 如果url过长,url就会被截取,

这样会导致数据的异常,post是安全。


HttpURLConnection

// 1 创建路径  

// 2 通过路径拿到连接  

// 3 设置请求方式  

// 4 设置超时时间  

// 5 判断是否连接成功 n


Get

// path 例: http://10.0.2.2:8081/xxxx/xxxx
StringBuilder sb = new StringBuilder(path);
// 拼接参数 例: ?Name=xxx&age =xxx
                if(!params.isEmpty()){
                sb.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                        String key = entry.getKey();
                        String value = entry.getValue();
                        sb.append(key).append("=").append(value);
                        sb.append("&");

                }
                }
                sb.deleteCharAt(sb.length() - 1);
                try {
                        URL url = new URL(sb.toString());
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
             // 设置请求方式里面的参数一定要全大写
                        conn.setRequestMethod("GET");
                        conn.setReadTimeout(5000);
                        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // -对web的反馈数据进行处理
                                InputStream is = conn.getInputStream();
                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                byte[] buffer = new byte[1024];
                                int len = 0;
                                while((len = is.read(buffer))!=-1)
                                {
                                        bos.write(buffer, 0, len);
                                }
                                String data = bos.toString();
                                flag = data.equals("success")?true:false;
                        }
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }

Post

// post不需要在路径后面拼接参数
StringBuilder sb = new StringBuilder();
                if(!params.isEmpty()){

                for (Map.Entry<String, String> entry : params.entrySet()) {
                        String key = entry.getKey();
                        String value = entry.getValue();
                        sb.append(key).append("=").append(value);
                        sb.append("&");

                        }   
                }
                sb.deleteCharAt(sb.length() - 1);
                byte[] entity = sb.toString().getBytes();
                try {
                        URL url = new URL(path);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("POST");
                        conn.setReadTimeout(5000);
                        //Content-Type: application/x-www-form-urlencoded
                        //Content-Length: 24
// 除了设置请求类型和请求超时时长外,一定要设置内容类型和内容长度
                        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                        conn.setRequestProperty("Content-Length", entity.length+"");
// 设置允许输出
// 输出请求实体 例 name=xxx&age=xx
                        conn.setDoOutput(true);
                        OutputStream os = conn.getOutputStream();
                        os.write(entity);
                        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                InputStream is = conn.getInputStream();
                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                byte[] buffer = new byte[1024];
                                int len = 0;
                                while((len = is.read(buffer))!=-1)
                                {
                                        bos.write(buffer, 0, len);
                                }
                                String data = bos.toString();
                                flag = data.equals("success")?true:false;
                        }
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }


HttpClient

// 我们可以把它看作一个浏览器

特点:

1.需要引入第三方jar(android内部提供)

2.基于HttpURLConnection的封装

3.能够满足复杂的需求(CookitSession

4.基本操作简单

流程

拿到httpClient对象

创建请求方式对象(需要访问路径)    httpGet()

3 httpClient对象使用execute执行请求对象

得到返回对象,从返回对象上拿到返回码

对返回码进行判断

从返回对象上拿到返回值


Get

StringBuilder sb = new StringBuilder(path);
                if(!params.isEmpty()){
                sb.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                        String key = entry.getKey();
                        String value = entry.getValue();
                        sb.append(key).append("=").append(value);
                        sb.append("&");

                        }
                sb.deleteCharAt(sb.length() - 1);
                }
                // 可以看作浏览器
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet request = new HttpGet(sb.toString());
                // 执行请求
                try {
                        HttpResponse response = httpClient.execute(request);
                        StatusLine line = response.getStatusLine();
                        int statueCode = line.getStatusCode();
                        if(statueCode == HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
                        InputStream is = entity.getContent();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                byte[] buffer = new byte[1024];
                                int len = 0;
                                while((len = is.read(buffer))!=-1)
                                {
                                        bos.write(buffer, 0, len);
                                }
                                String data = bos.toString();
                                flag = data.equals("success")?true:false;

                        }
                } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }


Post             

HttpClient httpClient = new DefaultHttpClient();
                HttpPost request = new HttpPost(path);

                // 执行请求
// 请求实体 NameValuePair
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                for(Map.Entry<String, String> entry:params.entrySet())
                {
                                String name = entry.getKey();
                                String value = entry.getValue();
                                NameValuePair nvp = new BasicNameValuePair(name, value);
                                parameters.add(nvp);
                }
                UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(parameters);
                // 发送请求实体
request.setEntity(uefe);


                        HttpResponse response = httpClient.execute(request);
                        StatusLine line = response.getStatusLine();
                        int statueCode = line.getStatusCode();
                        if(statueCode == HttpStatus.SC_OK)
                        {
                                HttpEntity entity = response.getEntity();
                                InputStream is = entity.getContent();
                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                byte[] buffer = new byte[1024];
                                int len = 0;
                                while((len = is.read(buffer))!=-1)
                                {
                                        bos.write(buffer, 0, len);
                                }
                                String data = bos.toString();

获取图片

ImageView img = (ImageView) findViewById(R.id.iv);
     
        URL url;
                try {
                        url = new URL("http://10.0.2.2:8081/myssh/login.png");
               
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setReadTimeout(2000);
      
        if(conn.getResponseCode() == 200)
        {
                InputStream is = conn.getInputStream();
                img.setImageBitmap(BitmapFactory.decodeStream(is));
        }
                }  catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }

xml

// 拿到连接对象使用pull解析读取


Json

// 拿到连接对象读取完json格式的字符串

使用JSONArray解析

String json = bos.toString();
                        JSONArray jsonArray = new JSONArray(json);
                        for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject object = jsonArray.getJSONObject(i);
        list.add(new Users(object.getInt("id"), object.getString("name"), object.getString("pwd")));
        }

你可能感兴趣的:(android,高薪就业,andorid宝典,android从零开始)