Android中Http接口调用

Android中Http接口调用,第1张

概述今天我们要说的Http接口访问是使用HttpURLConnection对象实现的。有人会问了,为什么要说这个?咱们都用okhttp了,或者用Retrofit,再不济用的也是别人写好的二次封装的,咋就整这么原始的东西出来了,难道博主用的是这个。这......我也不用这个。但是本着总得会的原则,我在这里总结一下。1

今天我们要说的http接口访问是使用httpURLConnection对象实现的。有人会问了,为什么要说这个?咱们都用okhttp了,或者用Retrofit,再不济用的也是别人写好的二次封装的,咋就整这么原始的东西出来了,难道博主用的是这个。这......我也不用这个。但是本着总得会的原则,我在这里总结一下。

1.获取httpURLConnection对象
URL url = new URL("");httpURLConnection conn = (httpURLConnection) url.openConnection();
2.httpURLConnection相关APIsetRequestMethod:设置请求类型。GET表示get请求,POST表示post请求。setConnectTimeout:设置连接的超时时间。setReadTimeout:设置读取的超时时间。setRequestProperty:设置请求包头的属性信息。setDoOutput:设置是否允许发送数据。如果用到getoutputStream方法,setDoOuput就必须设置为true。因为POST方式肯定会发送数据,所以POST调用时必须设置该方法。getoutputStream:获取http输出流。调用该函数返回一个OutputStream对象,接着依次调用该对象的write和flush方法写入要发送的数据。connect:建立http连接。setDoinput:设置是否允许接收数据。如果用到getinputStream方法,setDoinput就必须设置为true(其实也不必手动设置,因为默认就是true)。getinputStream:获取http输入流。调用该函数返回一个inputStream对象,接着调用该对象的read方法读出接收的数据。getResponseCode:获取http返回码。getheaderFIEld:获取应答数据包头的指定属性值。getheaderFIElds:获取应答数据包头的所有属性列表。disconnect:断开http连接。3.httpURLConnection请求示例--简单的get、post请求
public class httpRequestUtil {    private static final String TAG = "httpRequestUtil";    // 设置http连接的头部信息    private static voID setConnheader(httpURLConnection conn, String method, httpReqData req_data)            throws ProtocolException {        // 设置请求方式,常见的有GET和POST两种        conn.setRequestMethod(method);        // 设置连接超时时间        conn.setConnectTimeout(5000);        // 设置读写超时时间        conn.setReadTimeout(10000);        // 设置数据格式        conn.setRequestProperty("Accept", "*/*");        // IE使用//        conn.setRequestProperty("Accept-Language", "zh-CN");//        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; windows NT 6.1; WOW64; TrIDent/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C)");        // firefox使用        // 设置文本语言        conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");        // 设置用户代理        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 firefox/33.0");        // 设置编码格式        conn.setRequestProperty("Accept-EnCoding", "gzip, deflate");        if (!req_data.content_type.equals("")) {            // 设置内容类型            conn.setRequestProperty("Content-Type", req_data.content_type);        }        if (!req_data.x_requested_with.equals("")) {            // 判断request来自AJAX请求还是传统请求            conn.setRequestProperty("X-Requested-With", req_data.x_requested_with);        }        if (!req_data.referer.equals("")) {            // 设置跳转来源            conn.setRequestProperty("Referer", req_data.referer);        }        if (!req_data.cookie.equals("")) {            // 设置秘密纸条            conn.setRequestProperty("cookie", req_data.cookie);            Log.d(TAG, "setConnheader cookie=" + req_data.cookie);        }    }    private static String getRespcookie(httpURLConnection conn, httpReqData req_data) {        String cookie = "";        Map<String, List<String>> headerFIElds = conn.getheaderFIElds();        if (headerFIElds != null) {            List<String> cookies = headerFIElds.get("Set-cookie");            if (cookies != null) {                for (String cookie_item : cookies) {                    cookie = cookie + cookie_item + "; ";                }            } else {                cookie = req_data.cookie;            }        } else {            cookie = req_data.cookie;        }        Log.d(TAG, "cookie=" + cookie);        return cookie;    }    // get文本数据    public static httpRespData getData(httpReqData req_data) {        httpRespData resp_data = new httpRespData();        try {            URL url = new URL(req_data.url);            // 创建指定网络地址的http连接            httpURLConnection conn = (httpURLConnection) url.openConnection();            setConnheader(conn, "GET", req_data);            conn.connect(); // 开始连接            // 对输入流中的数据进行解压,得到原始的应答字符串            resp_data.content = StreamTool.getUnzipStream(conn.getinputStream(),                    conn.getheaderFIEld("content-encoding"), req_data.charset);            resp_data.cookie = conn.getheaderFIEld("Set-cookie");            conn.disconnect(); // 断开连接        } catch (Exception e) {            e.printstacktrace();            resp_data.err_msg = e.getMessage();        }        return resp_data;    }    // get图片数据    public static httpRespData getimage(httpReqData req_data) {        httpRespData resp_data = new httpRespData();        try {            URL url = new URL(req_data.url);            // 创建指定网络地址的http连接            httpURLConnection conn = (httpURLConnection) url.openConnection();            setConnheader(conn, "GET", req_data);            conn.connect(); // 开始连接            // 从http连接获取输入流            inputStream is = conn.getinputStream();            // 对输入流中的数据进行解码,得到位图对象            resp_data.bitmap = BitmapFactory.decodeStream(is);            resp_data.cookie = conn.getheaderFIEld("Set-cookie");            conn.disconnect(); // 断开连接        } catch (Exception e) {            e.printstacktrace();            resp_data.err_msg = e.getMessage();        }        return resp_data;    }    // post的内容放在url中    public static httpRespData postUrl(httpReqData req_data) {        httpRespData resp_data = new httpRespData();        String s_url = req_data.url;        if (req_data.params != null && !req_data.params.toString().isEmpty()) {            s_url += "?" + req_data.params.toString();        }        Log.d(TAG, "s_url=" + s_url);        try {            URL url = new URL(s_url);            // 创建指定网络地址的http连接            httpURLConnection conn = (httpURLConnection) url.openConnection();            setConnheader(conn, "POST", req_data);            conn.setDoOutput(true);            conn.connect(); // 开始连接            resp_data.content = StreamTool.getUnzipStream(conn.getinputStream(),                    conn.getheaderFIEld("content-encoding"), req_data.charset);            resp_data.cookie = conn.getheaderFIEld("Set-cookie");            conn.disconnect(); // 断开连接        } catch (Exception e) {            e.printstacktrace();            resp_data.err_msg = e.getMessage();        }        return resp_data;    }    // post的内容放在输出流中    public static httpRespData postData(httpReqData req_data) {        req_data.content_type = "application/x-www-form-urlencoded";        httpRespData resp_data = new httpRespData();        String s_url = req_data.url;        Log.d(TAG, "s_url=" + s_url + ", params=" + req_data.params.toString());        try {            URL url = new URL(s_url);            // 创建指定网络地址的http连接            httpURLConnection conn = (httpURLConnection) url.openConnection();            setConnheader(conn, "POST", req_data);            conn.setDoOutput(true);            conn.setDoinput(true);            conn.connect(); // 开始连接            PrintWriter out = new PrintWriter(conn.getoutputStream());            out.print(req_data.params.toString());            out.flush();            // 对输入流中的数据进行解压,得到原始的应答字符串            resp_data.content = StreamTool.getUnzipStream(conn.getinputStream(),                    conn.getheaderFIEld("content-encoding"), req_data.charset);            resp_data.cookie = getRespcookie(conn, req_data);            conn.disconnect(); // 断开连接        } catch (Exception e) {            e.printstacktrace();            resp_data.err_msg = e.getMessage();        }        return resp_data;    }    // post的内容分段传输    public static httpRespData postMultIData(httpReqData req_data, Map<String, String> map) {        httpRespData resp_data = new httpRespData();        String s_url = req_data.url;        Log.d(TAG, "s_url=" + s_url);        String end = "\r\n";        String hyphens = "--";        try {            URL url = new URL(s_url);            httpURLConnection conn = (httpURLConnection) url.openConnection();            setConnheader(conn, "POST", req_data);            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + req_data.boundary);            conn.setRequestProperty("Cache-Control", "no-cache");            conn.setDoOutput(true);            conn.setDoinput(true);            StringBuilder buffer = new StringBuilder();            Log.d(TAG, "map.size()=" + map.size());            for (String str : map.keySet()) {                buffer.append(hyphens + req_data.boundary + end);                buffer.append("Content-disposition: form-data; name=\"");                buffer.append(str);                buffer.append("\"" + end + end);                buffer.append(map.get(str));                buffer.append(end);                Log.d(TAG, "key=" + str + ", value=" + map.get(str));            }            if (map.size() > 0) {                buffer.append(hyphens + req_data.boundary + end);                byte[] param_data = buffer.toString().getBytes(req_data.charset);                OutputStream out = conn.getoutputStream();                out.write(param_data);                out.flush();            }            conn.connect(); // 开始连接            // 对输入流中的数据进行解压,得到原始的应答字符串            resp_data.content = StreamTool.getUnzipStream(conn.getinputStream(),                    conn.getheaderFIEld("content-encoding"), req_data.charset);            resp_data.cookie = conn.getheaderFIEld("Set-cookie");            conn.disconnect(); // 断开连接        } catch (Exception e) {            e.printstacktrace();            resp_data.err_msg = e.getMessage();        }        return resp_data;    }}
4.注意事项

除此之外,AndroID9开始默认只能访问以https开头的安全地址,不能直接访问http打头的网络地址。如果应用仍想访问以http开头的普通地址,就得修改AndroIDManifest.xml,给application节点添加如下属性,表示继续使用http明文地址:

androID:usesCleartextTraffic="true"

 

总结

以上是内存溢出为你收集整理的Android中Http接口调用全部内容,希望文章能够帮你解决Android中Http接口调用所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1019492.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存