android网络连接几种方式总结

HTTP协议全名超文本协议,是应用层的协议,特点是客户端发送的每次请求都需要服务器回送响应,在请求借宿后会主动释放连接。

http 1.0 request和response是一次连接,即短连接。

而http1.1 可以在响应后保持连接,保持连接,可以传送多个HTTP请求和响应. 多个请求和响应可以重叠,多个请求和响应可以同时进行,即长连接。

Connection请求头的值为Keep-Alive

时,客户端通知服务器返回本次请求结果后保持连接;Connection请求头的值为close时,客户端通知服务器返回本次请求结果后关闭连接。HTTP 1.1还提供了与身份认证、状态管理和Cache缓存等机制相关的请求头和响应头。

 

在Android中,使用HTTP协议在客户端和服务端之间交互
有两种方式(写法):使用

 

一种是使用apache的HttpClient,Android已经集成了HttpClient,另一种是HttpURLConnection

 

HttpClient:

      一般步骤:1.创建HttpClient对象

                     2.创建get或post请求的对象HttpGet或HttpPost

                    3.两种方式使用上主要在于封装数据的差异,get直接在url后拼接,而post需要使用setEntity(HttpEntity entity)方法来设置请求参数,HttpEntity相当于一个报文的实体。

                     4.调用HttpCilent对象的execute(HttpUriReques reques)发送请求,返回一个HttpResponse对象

                     5.如果要接受数据调用HttpResponse的对应方法获取服务器的响应头,响应内容等。

get请求:

//协议参数对象
        BasicHttpParams httpParams = new BasicHttpParams();
 //设置请求时间
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
//设置响应时间
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
//http客户端对象
        HttpClient client = new DefaultHttpClient(httpParams);
//get请求对象,直接在url后添加参数
        HttpGet get = new HttpGet(URL_USER_LOGIN + "?loginName=" + loginName + "&loginPassword=" + loginPassword);
//http响应对象
        HttpResponse response = client.execute(get);
 //获得响应码
        int responseStatusCode = response.getStatusLine().getStatusCode();
        Log.d(TAG, String.valueOf(responseStatusCode));
        if (responseStatusCode != HttpStatus.SC_OK) {
//如果响应码不是200,抛出一个自定义的异常
            throw new ServiceRulesException(MSGTools.SERVER_ERROR);
        }
//获得entity中的数据
        String results = EntityUtils.toString(response.getEntity());
        Log.d(TAG, results);

post请求:

        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
// 创建那个HttpClient对象
        HttpClient client = new DefaultHttpClient(httpParams);
// post请求:不是把值放在URL后面,不是在请求头,请求正体里面
//URL_USER_LOGIN为url请求地址
        HttpPost post = new HttpPost(URL_USER_LOGIN);
//用NameValuePair(一种Key-value pair)封装传递的值
        NameValuePair paramLoginName = new BasicNameValuePair("loginName", loginName);
        NameValuePair paramLoginPassword = new BasicNameValuePair("loginPassword", loginPassword);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(paramLoginName);
        nameValuePairs.add(paramLoginPassword);
// 值封装到post
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
        HttpResponse response = client.execute(post);
        int responseStatusCode = response.getStatusLine().getStatusCode();
//httpentity可以获得string或stream,然后进行操作
        results = EntityUtils.toString(response.getEntity());

 

 

HttpURLConnnection

   关于这个我发现有个讲的很详细的文章,这是地址http://www.blogjava.net/supercrsky/articles/247449.html,也可以看我文章里转载的。

   主要步骤:

1.创建一个Url对象,get的参数依然拼在地址后面

2.通过url.openConnection()获得connection

 URLConnection urlConnection = url.openConnection();

3.设置connection的各种参数

4.urlConnection.connect()执行连接

5.要传送数据就获得输出流out,写数据进去

// 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法, 
// 所以在开发中不调用上述的connect()也可以)。 
OutputStream outStrm = httpUrlConnection.getOutputStream(); 

 

6.获取数据要通过输入流in获取,由你自己进行处理

 

get方式代码片段:

 

Bitmap bitmap = null;
URL url = null;
InputStream in = null;
HttpURLConnection urlConnection = null;

try {
   url = new URL("http://192.168.130.55:8080/getImage.jpg?id=2");
   urlConnection = (HttpURLConnection) url.openConnection();
   urlConnection.setConnectTimeout(10000);
  urlConnection.setReadTimeout(20000);
// 允许读数据
// urlConnection.setDoInput(true);
/ 允许写数据
// urlConnection.setDoOutput(true);
 // 设置缓存
// urlConnection.setUseCaches(false);
// urlConnection.setRequestMethod("GET");
  urlConnection.connect();
   in = new BufferedInputStream(urlConnection.getInputStream());
   bitmap = BitmapFactory.decodeStream(in);
   } finally {
    if(in != null) {
     in.close();
    }
    if(urlConnection != null) {
      urlConnection.disconnect();
    }
   }

 

post方式代码片段:

        URL url = null;
        HttpURLConnection urlConnection = null;
        // 对于URLConnection来说,向服务器发送数据是输出流
        OutputStream out = null;
        // 对于URLConnection来说,从服务器接手数据是输入流
        InputStream in = null;
        String results = null;
        try {
            // method=province 
            // method=city&id=1
            // method=area&id=5
            Map<String, String> params = new HashMap<String, String>();
            params.put("method", "province");
            byte[] data = setPostPassParams(params).toString().getBytes();
            url = new URL("http://192.168.130.55:8080/remoteGetGategory.do");
            urlConnection = (HttpURLConnection) url.openConnection();
            // 请求连接超时
            urlConnection.setConnectTimeout(20 * 1000);
            // 响应超时
            urlConnection.setReadTimeout(20 * 1000);
            // 当前连接可以读取数据
            urlConnection.setDoInput(true);
            // 当前连接可以写入数据
            urlConnection.setDoOutput(true);
            // 请求方式为POST
            urlConnection.setRequestMethod("POST");
            // 取消缓存
            urlConnection.setUseCaches(false);
            // 常规text/html提交
            urlConnection.setRequestProperty("Content-Type",
                                "application/x-www-form-urlencoded");
            
            urlConnection.setRequestProperty("Content-Length",
                    String.valueOf(data.length));
            //urlConnection.connect();
            // 在这个连接上获得输出流
            out = urlConnection.getOutputStream();
            // 向服务器去传递数据
            out.write(data);
            out.flush();
            
            int responseCode = urlConnection.getResponseCode();
            if(responseCode != HttpURLConnection.HTTP_OK) {
                throw new Exception("服务器出错");
            }
            // 是从服务器接收的数据
            in = urlConnection.getInputStream();
            
            results = parseResponseResults(in);
        } finally {
            if(in != null) {
                in.close();
            }
            if(out != null) {
                out.close();
            }
            if(urlConnection != null) {
                urlConnection.disconnect();
            }
        }

更多可以参考android官网地址:http://developer.android.com/reference/java/net/HttpURLConnection.html

posted @ 2014-05-12 12:02  晴天雨植  阅读(1075)  评论(0编辑  收藏  举报