【Android-HTTP】关于HTTP方面的总结

**HTTP(HyperText Transfer Protocol 超文本传输协议),默认端口80
在拜读了众多大神的博客后,得出以下的结论:
在使用HTTP方面有两种:

这两种方式都支持HTTPS协议、以流的形式进行上传和下载、配置超时时间、IPv6、以及连接池等功能。
- HttpClient:用于Android 2.2 及 以下版本。使用DefaultHttpClient实例化HttpClient对象。
- HttpURLConnection: 用于Android 2.3 及 以上版本。HttpURLConnection 是轻量级的HTTP客户端。相比HTTPClient,HTTPURLConnection的使用更加简单,并且扩展性也更好。
HTTPClient(以post方式请求)实例:**

 BufferedReader in = null;  
        try {  
            HttpClient client = new DefaultHttpClient();  
            HttpPost request = new HttpPost(地址);  
            //使用NameValuePair来保存要传递的Post参数 
            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();  
            //添加要传递的参数 
            postParameters.add(new BasicNameValuePair("id", "123"));  
            postParameters.add(new BasicNameValuePair("password", "123"));  
            //实例化UrlEncodedFormEntity对象 
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(  
                    postParameters);  
            //使用HttpPost对象来设置UrlEncodedFormEntity的Entity 
            request.setEntity(formEntity);  
            HttpResponse response = client.execute(request);  
            in = new BufferedReader(  
                    new InputStreamReader(  
                            response.getEntity().getContent()));  
            StringBuffer string = new StringBuffer("");  
            String lineStr = "";  
            while ((lineStr = in.readLine()) != null) {  
                string.append(lineStr + "\n");  
            }  
            in.close();  
            String resultStr = string.toString();  
            System.out.println(resultStr);  
        } catch(Exception e) {  
            // Do something about exceptions 
        } finally {  
            if (in != null) {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }

HTTPURLConnection(get方式请求)实例:

 URL url = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try
        {
            url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            if (conn.getResponseCode() == 200)
            {
                is = conn.getInputStream();
                baos = new ByteArrayOutputStream();
                int len = -1;
                byte[] buf = new byte[128];

                while ((len = is.read(buf)) != -1)
                {
                    baos.write(buf, 0, len);
                }
                baos.flush();
                return baos.toString();
            } else
            {
                throw new RuntimeException(" responseCode is not 200 ... ");
            }

        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                if (is != null)
                    is.close();
            } catch (IOException e)
            {
            }
            try
            {
                if (baos != null)
                    baos.close();
            } catch (IOException e)
            {
            }
            conn.disconnect();
        }

**GET请求方式是通过把参数键值对附加在url后面来传递的,是文本方式的,参数直接暴露在浏览器的地址栏中,安全性相对较弱。
POST方式就传输方式,将参数打包在http报头中传输,可以是二进制的,不会暴露在浏览器的地址栏中,相当安全,不过相当于GET请求方式,参数获取会变慢,处理效率也会随之降低。**

现在OkHttp慢慢的取代了原本的网络请求。OkHttp更加高效,简便。
如下(post请求方式)

//创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
Request request = buildMultipartFormRequest(
        url, new File[]{file}, new String[]{fileKey}, null);
FormEncodingBuilder builder = new FormEncodingBuilder();   
builder.add("username","hello");

Request request = new Request.Builder()
                   .url(url)
                .post(builder.build())
                .build();
 mOkHttpClient.newCall(request).enqueue(new Callback(){});

(Get请求方式):

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
return response.body().string();
    } else {        
    throw new IOException("Unexpected code " + response);
    }
}

你可能感兴趣的:(android,http)