Android http 的使用

简介: 1、okHttp        https://github.com/square/okhttp   2、okhttp-utils       https://github.com/hongyangAndroid/okhttp-utils   3、NoHttp       https://github.
1、okHttp

       https://github.com/square/okhttp

 

2、okhttp-utils

      https://github.com/hongyangAndroid/okhttp-utils

 

3、NoHttp

      https://github.com/yanzhenjie/NoHttp

 

4、okhttp-OkGo

     https://github.com/jeasonlzy/okhttp-OkGo

 

5、最原生的http

package www.yiba.com.wifisdk.http;

import android.os.Build;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;

public class HttpUtil {

    private static final int TIMEOUT_IN_MILLIONS = 25000;

    /**
     * Get请求,获得返回数据
     * @param urlStr
     * @return
     * @throws Exception
     */
    public static String doGet(String urlStr , Callback callback) {
        URL url = null;
        URLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            url = new URL(urlStr);
            int responseCode = -1;
            if (urlStr.toLowerCase().startsWith("https")) {
                conn = url.openConnection();
                ((HttpsURLConnection) conn).setRequestMethod("GET");
                conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
                conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                if (Build.VERSION.SDK != null
                        && Build.VERSION.SDK_INT > 13) {//http://www.tuicool.com/articles/7FrMVf
                    conn.setRequestProperty("Connection", "close");
                }
                responseCode = ((HttpsURLConnection) conn).getResponseCode();
            } else {
                conn = url.openConnection();
                ((HttpURLConnection) conn).setRequestMethod("GET");
                conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
                conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                if (Build.VERSION.SDK != null
                        && Build.VERSION.SDK_INT > 13) {//http://www.tuicool.com/articles/7FrMVf
                    conn.setRequestProperty("Connection", "close");
                }
                responseCode = ((HttpURLConnection) conn).getResponseCode();
            }
            if (responseCode == 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();
                if ( callback != null ){
                    callback.ok( baos.toString() );
                }
                return baos.toString();
            } else {
                if ( callback != null ){
                    callback.fail();
                }
                throw new RuntimeException(" responseCode is not 200 ... ");
            }

        } catch (Exception e) {
            if ( callback != null ){
                callback.timeOut();
            }
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (baos != null)
                    baos.close();
            } catch (IOException e) {
            }
            if (conn != null) {
                if (urlStr.toLowerCase().startsWith("https")) {
                    ((HttpsURLConnection) conn).disconnect();
                } else {
                    ((HttpURLConnection) conn).disconnect();
                }
            }
        }
        return null;
    }


    public static String doPost(String url, String param , Callback callback ) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        URLConnection conn = null;
        try {
            URL realUrl = new URL(url);
            //打开和URL之间的连接
            conn =  realUrl.openConnection();
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            if (url.toLowerCase().startsWith("https")) {
                ((HttpsURLConnection) conn).setRequestMethod("POST");
            } else {
                ((HttpURLConnection) conn).setRequestMethod("POST");
            }
            conn.setRequestProperty("charset", "utf-8");
            conn.setUseCaches(false);
            //发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);

            if (param != null && !param.trim().equals("")) {
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
            }

            int responseCode = ((HttpURLConnection) conn).getResponseCode();
            if ( responseCode == 200 ){
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }

                if ( callback != null ){
                    callback.ok( result );
                }
            }else {
                if ( callback != null ){
                    callback.fail();
                }
            }
        } catch (Exception e) {
            if ( callback != null ){
                callback.timeOut();
            }
            e.printStackTrace();
        }
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            if (conn != null) {
                if (url.toLowerCase().startsWith("https")) {
                    ((HttpsURLConnection) conn).disconnect();
                } else {
                    ((HttpURLConnection) conn).disconnect();
                }
            }
        }
        return result;
    }

    public interface Callback{
        void ok( String result ) ;
        void fail();
        void timeOut() ;
    }

}

 

6、对原生http的简易封装

      6.1 HttpCall http 请求结果的实体类

      

package www.yiba.com.analytics.http;

/**
 * Created by ${zyj} on 2016/8/18.
 */
public class HttpCall {

    private ResponseType httpQuestType  ;
    private String result ;

    public ResponseType getHttpQuestType() {
        return httpQuestType;
    }

    public void setHttpQuestType(ResponseType httpQuestType) {
        this.httpQuestType = httpQuestType;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }
}

  

      6.2 ResponseType http 请求结果的类型

package www.yiba.com.analytics.http;

/**
 * Created by ${zyj} on 2016/8/18.
 */
public enum ResponseType {

    OK("请求成功") , FAIL("请求失败") , TIMEOUT("请求超时") ;

    private String name ;

    private ResponseType(String name ){
        this.name = name ;
    }

    public String getName() {
        return name;
    }
}

  

      6.3 HttpUtil 包含 get 和 post请求

package www.yiba.com.analytics.http;

import android.os.Build;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;

public class HttpUtil {

    private static final int TIMEOUT_IN_MILLIONS = 25000;

    /**
     * Get请求,获得返回数据
     * @param urlStr
     * @return
     * @throws Exception
     */
    public static HttpCall doGet(String urlStr , Callback callback) {
        URL url = null;
        URLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        HttpCall httpCall = new HttpCall() ;

        try {
            url = new URL(urlStr);
            int responseCode = -1;
            if (urlStr.toLowerCase().startsWith("https")) {
                conn = url.openConnection();
                ((HttpsURLConnection) conn).setRequestMethod("GET");
                conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
                conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                if (Build.VERSION.SDK != null
                        && Build.VERSION.SDK_INT > 13) {//http://www.tuicool.com/articles/7FrMVf
                    conn.setRequestProperty("Connection", "close");
                }
                responseCode = ((HttpsURLConnection) conn).getResponseCode();
            } else {
                conn = url.openConnection();
                ((HttpURLConnection) conn).setRequestMethod("GET");
                conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
                conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                if (Build.VERSION.SDK != null
                        && Build.VERSION.SDK_INT > 13) {//http://www.tuicool.com/articles/7FrMVf
                    conn.setRequestProperty("Connection", "close");
                }
                responseCode = ((HttpURLConnection) conn).getResponseCode();
            }
            if (responseCode == 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();
                if ( callback != null ){
                    callback.ok( baos.toString() );
                }
                if ( httpCall != null ){
                    httpCall.setHttpQuestType( ResponseType.OK  );
                    httpCall.setResult( baos.toString() );
                }

            } else {
                if ( callback != null ){
                    callback.fail();
                }
                if ( httpCall != null ){
                    httpCall.setHttpQuestType( ResponseType.FAIL  );
                    httpCall.setResult( "" );
                }
            }

        } catch (Exception e) {
            if ( callback != null ){
                callback.timeOut();
            }
            if ( httpCall != null ){
                httpCall.setHttpQuestType( ResponseType.TIMEOUT  );
                httpCall.setResult( "" );
            }
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (baos != null)
                    baos.close();
            } catch (IOException e) {
            }
            if (conn != null) {
                if (urlStr.toLowerCase().startsWith("https")) {
                    ((HttpsURLConnection) conn).disconnect();
                } else {
                    ((HttpURLConnection) conn).disconnect();
                }
            }

            return httpCall ;
        }
    }


    public static HttpCall doPost(String url, String param , Callback callback ) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        URLConnection conn = null;
        HttpCall httpCall = new HttpCall() ;

        try {
            URL realUrl = new URL(url);
            //打开和URL之间的连接
            conn =  realUrl.openConnection();
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type",
                    "application/json");
            if (url.toLowerCase().startsWith("https")) {
                ((HttpsURLConnection) conn).setRequestMethod("POST");
            } else {
                ((HttpURLConnection) conn).setRequestMethod("POST");
            }
            conn.setRequestProperty("charset", "utf-8");
            conn.setUseCaches(false);
            //发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);

            if (param != null && !param.trim().equals("")) {
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
            }

            int responseCode = ((HttpURLConnection) conn).getResponseCode();
            if ( responseCode == 200 ){
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }

                if ( callback != null ){
                    callback.ok( result );
                }

                if ( httpCall != null ){
                    httpCall.setHttpQuestType( ResponseType.OK  );
                    httpCall.setResult( result );
                }

            }else {
                if ( callback != null ){
                    callback.fail();
                }
                if ( httpCall != null ){
                    httpCall.setHttpQuestType( ResponseType.FAIL  );
                    httpCall.setResult( "" );
                }

            }
        } catch (Exception e) {
            if ( callback != null ){
                callback.timeOut();
            }
            if ( httpCall != null ){
                httpCall.setHttpQuestType( ResponseType.TIMEOUT  );
                httpCall.setResult( "" );
            }
            e.printStackTrace();
        }
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            if (conn != null) {
                if (url.toLowerCase().startsWith("https")) {
                    ((HttpsURLConnection) conn).disconnect();
                } else {
                    ((HttpURLConnection) conn).disconnect();
                }
            }
            return httpCall ;
        }
    }

    public interface Callback{
        void ok(String result) ;
        void fail();
        void timeOut() ;
    }

}

  

      6.4 如何使用

private void httpGet(){

        //get 用法1
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtil.doGet("http://www.baidu.com",  new HttpUtil.Callback() {
                    @Override
                    public void ok(String result) {
                        //请求成功
                    }

                    @Override
                    public void fail() {
                        //请求失败
                    }

                    @Override
                    public void timeOut() {
                        //请求超时
                    }
                }) ;
            }
        }) ;

        //get 用法2
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpCall httpCall = HttpUtil.doGet( "http://www.baidu.com"  , null ) ;
                switch ( httpCall.getHttpQuestType() ){
                    case OK:
                        //请求成功
                        break;
                    case FAIL:
                        //请求失败
                        break;
                    case TIMEOUT:
                        //请求超时
                        break;
                }
            }
        }) ;
    }


    private void httpPost(){

        //post 用法1
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtil.doPost("http://www.baidu.com", "post请求参数" , new HttpUtil.Callback() {
                    @Override
                    public void ok(String result) {
                        //请求成功
                    }

                    @Override
                    public void fail() {
                        //请求失败
                    }

                    @Override
                    public void timeOut() {
                        //请求超时
                    }
                }) ;
            }
        }) ;

        //post 用法2
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpCall httpCall = HttpUtil.doPost( "http://www.baidu.com" , "post请求参数" , null ) ;
                switch ( httpCall.getHttpQuestType() ){
                    case OK:
                        //请求成功
                        break;
                    case FAIL:
                        //请求失败
                        break;
                    case TIMEOUT:
                        //请求超时
                        break;
                }
            }
        }) ;
    }

  

7、http下载图片并且压缩bitmap  

//从网络下载bitmap
    private Bitmap downLoadBitmapFromNet( String urlString ){
        InputStream inputStream = null ;
        HttpURLConnection conn = null  ;
        Bitmap bitmap ;
        try {
            URL url = new URL( urlString ) ;
            conn = (HttpURLConnection) url.openConnection();
            inputStream = new BufferedInputStream( conn.getInputStream() ) ;

            inputStream.mark( inputStream.available() );

            //压缩图片
            BitmapFactory.Options options = new BitmapFactory.Options() ;
            options.inJustDecodeBounds = true ;
            BitmapFactory.decodeStream( inputStream , null , options ) ;
            options.inSampleSize = 4 ;
            options.inPreferredConfig = Bitmap.Config.RGB_565 ;
            options.inJustDecodeBounds = false ;

            inputStream.reset();
            bitmap = BitmapFactory.decodeStream( inputStream , null , options ) ;

            return  bitmap ;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if ( inputStream != null ){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if ( conn != null  ){
                conn.disconnect();
            }
        }
        return  null ;
    }

  需要注意的事项

1、并不是所有的inputStream都支持mark()方法的, 因为这里的 InputStream其实是 BufferedInputStream 。 BufferedInputStream 继承 InputStream 并且重写了里面的 mark() 、reset() 、markSupported()

 

相关文章
|
2月前
|
缓存 网络协议 安全
49. 【Android教程】HTTP 使用详解
49. 【Android教程】HTTP 使用详解
39 1
|
3月前
|
PHP Android开发
android通过http上传文件,服务器端用php写(原创)
android通过http上传文件,服务器端用php写(原创)
44 4
|
3月前
|
安全 搜索推荐 Android开发
Android安全性: 解释HTTPS在移动应用中的重要性。
Android安全性: 解释HTTPS在移动应用中的重要性。
52 0
|
2月前
|
XML API 网络安全
【安卓】在安卓中使用HTTP协议的最佳实践
【安卓】在安卓中使用HTTP协议的最佳实践
53 4
|
3月前
|
监控 Unix 应用服务中间件
Android-音视频学习系列-(八)基于-Nginx-搭建(rtmp、http)直播服务器
Android-音视频学习系列-(八)基于-Nginx-搭建(rtmp、http)直播服务器
|
3月前
|
安全 Android开发
Android之OKHttp基本使用和OKHttp发送https请求安全认证
Android之OKHttp基本使用和OKHttp发送https请求安全认证
88 0
|
6天前
|
XML 安全 Android开发
Flutter配置Android和IOS允许http访问
Flutter配置Android和IOS允许http访问
20 3
|
17天前
|
Java Android开发 UED
安卓scheme_url调端:如果手机上多个app都注册了 http或者https 的 intent。 调端的时候,调起哪个app呢?
当多个Android应用注册了相同的URL Scheme(如http或https)时,系统会在尝试打开这类链接时展示一个选择对话框,让用户挑选偏好应用。若用户选择“始终”使用某个应用,则后续相同链接将直接由该应用处理,无需再次选择。本文以App A与App B为例,展示了如何在`AndroidManifest.xml`中配置对http与https的支持,并提供了从其他应用发起调用的示例代码。此外,还讨论了如何在系统设置中管理这些默认应用选择,以及建议开发者为避免冲突应注册更独特的Scheme。
|
2月前
|
缓存 网络协议 安全
Android网络面试题之Http基础和Http1.0的特点
**HTTP基础:GET和POST关键差异在于参数传递方式(GET在URL,POST在请求体),安全性(POST更安全),数据大小限制(POST无限制,GET有限制),速度(GET较快)及用途(GET用于获取,POST用于提交)。面试中常强调POST的安全性、数据量、数据类型支持及速度。HTTP 1.0引入了POST和HEAD方法,支持多种数据格式和缓存,但每个请求需新建TCP连接。**
34 5
|
2月前
|
安全 网络协议 算法
Android网络基础面试题之HTTPS的工作流程和原理
HTTPS简述 HTTPS基于TCP 443端口,通过CA证书确保服务器身份,使用DH算法协商对称密钥进行加密通信。流程包括TCP握手、证书验证(公钥解密,哈希对比)和数据加密传输(随机数加密,预主密钥,对称加密)。特点是安全但慢,易受特定攻击,且依赖可信的CA。每次请求可能复用Session ID以减少握手。
34 2