当前位置:K88软件开发文章中心编程语言APP编程Android01 → 文章内容

7.1.3 Android HTTP请求方式:HttpURLConnection

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-12 6:26:43

本节引言:前面两节我们学习的都是一些概念性的东西,Http的协议以及协议头的一些东东,而本节我们就要堆码了,而本节学习的是Android为我们提供的Http请求方式之一:HttpURLConnection,除了这种,还有一种还有一种HttpClient,后者我们会下一节讲!不过前者一旦请求复杂起来,使用起来非常麻烦,而后者我们Java抓包也经常会用到,是Apache的,毕竟不是谷歌亲儿子,而在4.4版本HttpURLConnection已被替换成OkHttp了!好吧,与时俱进,决定讲完HttpClient也来会会这个OkHttp!对了,一般我们实际开发并不会用HttpURLConnection和HttpClient,使用别人封装好的第三方网络请求框架,诸如:Volley,android-async-http,loopj等,因为网络操作涉及到异步以及多线程,自己动手撸的话,很麻烦,所以实际开发还是直接用第三方!!当然学习下也无妨,毕竟第三方也是在这些基础上撸起来的,架构逼格高,各种优化!好的,话不多说,开始本节内容!1.HttpURLConnection的介绍答:一种多用途、轻量极的HTTP客户端,使用它来进行HTTP操作可以适用于大多数的应用程序。虽然HttpURLConnection的API提供的比较简单,但是同时这也使得我们可以更加容易地去使用和扩展它。继承至URLConnection,抽象类,无法直接实例化对象。通过调用openCollection()方法获得对象实例,默认是带gzip压缩的;2.HttpURLConnection的使用步骤使用HttpURLConnection的步骤如下:创建一个URL对象:URL url = new URL(https://www.baidu.com);调用URL对象的openConnection( )来获取HttpURLConnection对象实例:HttpURLConnection conn = (HttpURLConnection) url.openConnection();设置HTTP请求使用的方法:GET或者POST,或者其他请求方式比如:PUTconn.setRequestMethod("GET");设置连接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头conn.setConnectTimeout(6*1000);conn.setReadTimeout(6 * 1000);调用getInputStream()方法获得服务器返回的输入流,然后输入流进行读取了InputStream in = conn.getInputStream();最后调用disconnect()方法将HTTP连接关掉conn.disconnect();PS:除了上面这些外,有时我们还可能需要对响应码进行判断,比如200:if(conn.getResponseCode() != 200)然后一些处理 还有,可能有时我们并不需要传递什么参数,而是直接去访问一个页面,我们可以直接用:final InputStream in = new URL("url").openStream();然后直接读流,不过这个方法适合于直接访问页面的情况,底层实现其实也是return openConnection().getInputStream(),而且我们还不能设置一些请求头的东东,所以要不要这样写,你自己要掂量掂量!3.HttpURLConnection使用示例这里我们主要针对GET和POST请求写两个不同的使用示例,我们可以conn.getInputStream()获取到的是一个流,所以我们需要写一个类将流转化为二进制数组!工具类如下:StreamTool.java:/** * Created by Jay on 2015/9/7 0007. */public class StreamTool { //从流中读取数据 public static byte[] read(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while((len = inStream.read(buffer)) != -1) { outStream.write(buffer,0,len); } inStream.close(); return outStream.toByteArray(); }}接下来就可以开始撸我们的示例了!1)HttpURLConnection发送GET请求代码示例运行效果图:核心部分代码:布局:activity_main.xml<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/txtMenu" android:layout_width="match_parent" android:layout_height="48dp" android:background="#4EA9E9" android:clickable="true" android:gravity="center" android:text="长按我,加载菜单" android:textSize="20sp" /> <ImageView android:id="@+id/imgPic" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone" /> <ScrollView android:id="@+id/scroll" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone"> <TextView android:id="@+id/txtshow" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </ScrollView> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" /></LinearLayout>获取数据类:GetData.java:/** * Created by Jay on 2015/9/7 0007. */public class GetData { // 定义一个获取网络图片数据的方法: public static byte[] getImage(String path) throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置连接超时为5秒 conn.setConnectTimeout(5000); // 设置请求类型为Get类型 conn.setRequestMethod("GET"); // 判断请求Url是否成功 if (conn.getResponseCode() != 200) { throw new RuntimeException("请求url失败"); } InputStream inStream = conn.getInputStream(); byte[] bt = StreamTool.read(inStream); inStream.close(); return bt; } // 获取网页的html源代码 public static String getHtml(String path) throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.

[1] [2] [3] [4]  下一页


7.1.3 Android HTTP请求方式:HttpURLConnection