[Android]网络编程Httpclient类/HttpURLConnection类/okhttp框架

首先明确下网络编程需要一些基础概念

》输入输出流

InputStream之所以叫输入类,是因为它要把要需要读取的内容转化成输入流,再从它那里进行读取

OutputStream之所以叫输出类,是因为它首先需要与写入的目的地相关联,然后通过它进行写入。

输入是:把要读取的内容输入到输入流,在从输入流进行读取,所以是read()

输出是:把要输出的东西通过输出流输出到目的地,所以是write()

》关于Get和Post

一般来说,我们用到HTTP相关做网络请求,简便的我的理解,就是Get方式会将请求参数放到URL里,即追加到地址栏的方式,即请求网址+参数

所以get方式会限制数据字节长

而Post则是将数据放在编码里不会向外暴露,发送URL的时候,数据就这被发送的数据报里。不限制数据长度。

》URLConnection和HttpURLConnection

HttpURLConnection继承自URLConnection,差别在与HttpURLConnection仅仅针对Http连接

》状态码 表示服务器端返回的状态,如500表示错误,404表示资源不存在,我们一般关注200表示请求完成

======GET法=======HttpURLConnection===================

public class HttpUrlConnection {

    private static String PATH = "网址";

    public HttpUrlConnection() {
    }

    public void save(){
        InputStream inputStream = get();//这里就已经返回了请求到的数据

        //...这里进行IO流的读写操作即可


    }

    public InputStream get() {

        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;

        try {
            URL url = new URL(PATH);

            if (url != null) {

                //openConnection()返回的是一个URLconnection对象,表示到url所引用的远程对象的连接
                //所以用个已知的实现类httpURLConnection对象接收它吧

                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(3000);//设置网络超时时间
                httpURLConnection.setDoInput(true);//打开输入流

                //设置本次请求使用的方式
                httpURLConnection.setRequestMethod("GET");

                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode == 200) {
                    //这个时候就可取数据了
                    inputStream = httpURLConnection.getInputStream();//得到一个输入流

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return inputStream;
    }


}

======POST法=======HttpURLConnection===================

public class HttpPost {
    private static String PATH = "网址";
    private static URL url;

    public HttpPost() {
    }

    static {
        try {
            url = new URL(PATH);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }


    public void Dopost() {//模拟发送 
        Map<String, String> params = new HashMap<String, String>();
        params.put("username", "Tiffany");
        params.put("password", "1234567");
        httpPost(params, "utf-8");

    }

    //params填写参数用
    //encode 字节编码
    public static String httpPost(Map<String, String> params, String encode) {

        //初始化的字符串用来做请求体
        StringBuffer buffer = new StringBuffer();

        OutputStream outputStream = null;
        InputStream inputStream = null;

        try {
            if (params != null && !encode.isEmpty()) {

                for (Map.Entry<String, String> entry : params.entrySet()) {

                    //为了把用户输入的参数追加到buffer里面
                    buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&");

                }

                buffer.deleteCharAt(buffer.length() - 1);//删除最后的&


                try {

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(3000);//设置连接超时的时候
                    connection.setRequestMethod("POST");
                    connection.setDoInput(true);//向服务端获取数据
                    connection.setDoOutput(true);//向服务器写数据


                    //获得上传信息的字节大小和长度//!!!!!这里已经开始封装内部数据了
                    byte[] mydata = buffer.toString().getBytes();

                    //设置请求体的类型 数据被编码为名称/值对。这是标准的编码格式
                    connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                    connection.setRequestProperty("Content-Length",String.valueOf(mydata.length));


                    //获得输出流向服务器输出数据
                    outputStream = connection.getOutputStream();
                    outputStream.write(mydata);//把本地数据放进输出流,然后上传到服务器

                    //获得服务器响应的结果和状态码
                   int responseCode = connection.getResponseCode();
                    if (responseCode==200){

                        inputStream = connection.getInputStream();
                        return changeInputstream(inputStream,encode);//通过一个方法把输入流变成字符串

                    }




                } catch (IOException e) {

                    e.printStackTrace();

                }


            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        return "";
    }

    //将输入流变为指定编码的字符串
    public static String changeInputstream(InputStream inputStream,String encode){

        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();//内存流
        byte[] data = new byte[1024];
        int len = 0;
        String result = "";
        if (inputStream!=null){

            try {
                while ((len=inputStream.read(data))!=-1){

                    arrayOutputStream.write(data,0,len);//把输出流写进去

                }

                result = new String(arrayOutputStream.toByteArray(),encode);

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return result;
    }


}

=============Httpclient=======================

创建代表请求的对象,如果需要发送GET请求,则创建HttpGet对象,如果需要发送POST请求,则创建HttpPost对象。

由于现在Android Studio 已经取消的对Httpclient的引用而且推荐使用HttpURLConnection,而且还存在OKhttp框架,这里就不多讲述了

//用HttpClient发送请求,分为五步
//第一步:创建HttpClient对象70              
HttpClient httpCient = new DefaultHttpClient();
//第二步:创建代表请求的对象,参数是访问的服务器地址72      
 HttpGet httpGet = new HttpGet("http://www.baidu.com");             
try {
//第三步:执行请求,获取服务器发还的相应对象76            
 HttpResponse httpResponse = httpCient.execute(httpGet);
//第四步:检查相应的状态是否正常:检查状态码的值是200表示正常78                  
  if (httpResponse.getStatusLine().getStatusCode() == 200) {
 //第五步:从相应对象当中取出数据,放到entity当中80                
 HttpEntity entity = httpResponse.getEntity();
 String response = EntityUtils.toString(entity,"utf-8");
//将entity当中的数据转换为字符串
                     }

 
============= 
okhttp框架 
======================= 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值