socket编程socket编程,最初接触java用socket写过简单的聊天小软件。soc_安卓网络编程">
当前位置:   article > 正文

Android网络编程常用的三种方法_安卓网络编程

安卓网络编程

最近看了看以前的代码,发现很多东西不看不写慢慢忘记了,所以想总结下,首先想到的就是android下的网络编程。慢慢总结,慢慢完善。
首先android常用的有三种网络通信方式,socket编程、HttpClient、HttpURLConnection。网络下编程必须添加权限:

<uses-permission android:name="android.permission.INTERNET" />
  • 1

socket编程

socket编程,最初接触java用socket写过简单的聊天小软件。socket翻译过来是‘插座’的意思,计算机专业术语则称之为‘套接字’,用于描述IP地址和端口(可以从socket的初始化语句理解),是一个通信链的句柄,可以用来实现不同虚拟机或不同计算机之间的通信。android中暂时没用到过,用到了再更新。

HttpClient

HttpClient是Apache对java中的HttpURLClient接口的封装,主要引用org.apache.http.**。Google在2.3版本之前推荐使用HttpClient,因为这个封装包安全性高,bug较少。

使用方法:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;



public class HttpClientUtils {
    private static HttpClient httpClient;
    private static HttpClientUtils instance = null;

    public static synchronized HttpClientUtils getInstance() {
        if (instance == null) {
            instance = new HttpClientUtils();
        }
        return instance;
    }

    private HttpClientUtils() {
        // 学习volley请求队列,HttpClient使用单例模式
        if (httpClient == null) {
            httpClient = new DefaultHttpClient();
        }
    }
    /**
     * 以get方式发送请求,访问接口
     * @param uri链接地址
     * @return 响应数据
     */
    private static String doHttpGet(String uri) {
        BufferedReader reader = null;
        StringBuffer sb = null;
        String result = "";
        HttpGet request = new HttpGet(uri);
        try {
            // 发送请求,得到响应
            HttpResponse response = httpClient.execute(request);
            // 请求成功,statuscode返回200
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                sb = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != reader) {
                    reader.close();
                    reader = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != sb) {
            result = sb.toString();
        }
        return result;
    }

    /**
     * 以post方式发送请求,访问接口
     * @param uri链接地址
     * @return 响应数据
     */
    private static String doHttpPost(String uri) {
        BufferedReader reader = null;
        StringBuffer sb = null;
        String result = "";
        HttpPost request = new HttpPost(uri);

        // 保存要传递的参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // 添加参数
        params.add(new BasicNameValuePair("parameter", "以Post方式发送请求"));

        try {
            // 设置字符集
            HttpEntity entity = new UrlEncodedFormEntity(params, "utf-8");
            // 请求对象
            request.setEntity(entity);
            // 发送请求
            HttpResponse response = httpClient.execute(request);
            // 请求成功
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("post success");
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                sb = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭流
                if (null != reader) {
                    reader.close();
                    reader = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != sb) {
            result = sb.toString();
        }
        return result;
    }

}
  • 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
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133

HttpURLConnection

HttpURLConnection在java.net下,继承自URLConnection类,相对于HttpClient具有扩展性高、灵活性高,更轻量级的优点,所以Google在2.3版本之后推荐大家使用HttpURLConnection来操作网络请求。

使用方法:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class HttpURLConnectUtils {

    private static HttpURLConnectUtils instance = null;

    public static synchronized HttpURLConnectUtils getInstance() {
        if (instance == null) {
            instance = new HttpURLConnectUtils();
        }
        return instance;
    }

    private HttpURLConnectUtils() {
    }

    // post
    public String dohttppost(String mUrl) throws IOException {

        URL url = new URL(mUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();//初始化创建HttpURLConnection实例
        httpURLConnection.setConnectTimeout(5000);//推荐设置网络延时
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
        httpURLConnection.setRequestMethod("POST");
        //设置参数
        OutputStream outputStream = httpURLConnection.getOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        String params = new String();//这里简单设置参数
        params = "name=" + URLEncoder.encode("高冉", "GBK");
        objectOutputStream.writeBytes(params);
        objectOutputStream.flush();
        objectOutputStream.close();
        //接收返回值
        //String msg = httpURLConnection.getResponseMessage();// 接收简单string
        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuilder builder = new StringBuilder();
        for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine()) {
            builder.append(s);
        }
        return builder.toString();
    }

    // get
    public String dohttpget(String mUrl) throws IOException {
        URL url = new URL(mUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(5000);//推荐设置网络延时
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.connect();

        // String msg = httpURLConnection.getResponseMessage();

        InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        StringBuilder builder = new StringBuilder();
        for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine()) {
            builder.append(s);
        }

        return builder.toString();
    }
}
  • 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
  • 74

还需要注意一些细节:

1、post与get区别在于post将参数置于请求数据中,get则跟在url链接后面。
2、大文件下载操作要置于sd卡中,不要放在手机内存中操作,而且需要边读边写,不要使用Buffered做缓存。

到此android网络操作常用方法暂时总结完毕。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/574788
推荐阅读
相关标签
  

闽ICP备14008679号