Android 原生代码实现网络请求
来源:互联网 发布:她理财是真是假 知乎 编辑:程序博客网 时间:2024/05/22 00:32
本文导读
- 使用URL访问网络资源:下载图片
- 使用URLConnection进行网络请求:GET&POST
- 使用HttpURLConnection进行网络请求:GET&POST
- 原生代码实现及解析:注释
- Demo代码下载
使用URL访问网络资源
- URL对象代表统一资源定位器,指向互联网资源的指针,由协议名,主机,端口和资源组成。
- URI代表统一资源标识符,不能用于定位资源,唯一的作用就是解析。
- URL则包含一个可打开该资源书入输入流,因此可以说URL是URI的特例。
URL实现图片下载
private Bitmap bitmap;Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0x123) { //使用ImageView显示图片 ivUrl.setImageBitmap(bitmap); } } }; new Thread() { @Override public void run() { try { URL url = new URL("http://192.168.199.100:8080/image/D.png");//URl对象,指向本地服务器的一张图片 InputStream is = url.openStream();//打开输入流 bitmap = BitmapFactory.decodeStream(is);//解析成bitmap对象 handler.sendEmptyMessage(0x123);//handler机制UI显示图片 OutputStream os = openFileOutput("demon.png", MODE_PRIVATE);//打开一个文件对应的输入流 byte[] bytes = new byte[1024]; int has; while ((has = is.read(bytes)) > 0) { os.write(bytes, 0, has);//将URL对应的图片下载到本地 } is.close();//关闭流 os.close();//关闭流 } catch (Exception e) { e.printStackTrace(); } }}.start();
使用URLConnection进行网络请求
URL的openConnection返回一个URLConnection对象,表示与该URL建议通信连接。通过该对象,可以发送请求,读取资源。
创建URL连接,发生请求,读取资源步骤如下:
- 使用openConnection创建一个URLConnection对象
- 设置URLConnection的参数和普通请求属性
- GET请求,使用connect方法建立连接即可;POST请求,则需要获取URLConnection实例的输出流发送请求参数
- 访问资源的输入流读取数据
PS:必须先使用输出流发送请求参数,再使用输入流获取数据
实现URLConnection的GET,POST请求工具类
public class GetPostUrl { public static GetPostUrl getPost = new GetPostUrl();//单例 public static GetPostUrl getGetPost() { return getPost; } /** * 发送get请求 * * @param url * @return */ public static String get(final String url) { final StringBuilder sb = new StringBuilder(); FutureTask<String> task = new FutureTask<String>(new Callable<String>() { @Override public String call() throws Exception { BufferedReader br = null; InputStreamReader isr = null; URLConnection conn; try { URL geturl = new URL(url); conn = geturl.openConnection();//创建连接 conn.connect();//get连接 InputStreamReader isr = new InputStreamReader(conn.getInputStream());//输入流 br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { sb.append(line);//获取输入流数据 } System.out.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); } finally {//执行流的关闭 if (br != null) { try { if (br != null) { br.close(); } if (isr != null) { isr.close(); } } catch (IOException e) { e.printStackTrace(); } }} return sb.toString(); } }); new Thread(task).start(); String s = null; try { s = task.get();//异步获取返回值 } catch (Exception e) { e.printStackTrace(); } return s; } /** * POST请求 * * @param url url * @param map 请求参数的map集合形式 * @return */ public static String post(final String url, final Map<String, String> map) { final StringBuilder sb = new StringBuilder(); FutureTask<String> task = new FutureTask<String>(new Callable<String>() { @Override public String call() throws Exception { DataOutputStream out = null; BufferedReader br = null; URLConnection conn; URL posturl = new URL(url); try { conn = posturl.openConnection();//创建连接 conn.setDoInput(true);//post请求必须设置 conn.setDoOutput(true);//post请求必须设置 out = new DataOutputStream(conn .getOutputStream());//输出流 StringBuilder request = new StringBuilder(); for (String key : map.keySet()) { request.append(key + "=" + URLEncoder.encode(map.get(key), "UTF-8") + "&"); }//连接请求参数 out.writeBytes(request.toString());//输出流写入请求参数 out.flush(); out.close(); br = new BufferedReader(new InputStreamReader(conn.getInputStream()));//获取输入流 String line; while ((line = br.readLine()) != null) { sb.append(line); } System.out.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); } finally {//执行流的关闭 if (br != null) { br.close(); } if (out != null) { out.close(); } } return sb.toString(); } }); String s = null; new Thread(task).start(); try { s = task.get();//异步获取返回值 } catch (Exception e) { e.printStackTrace(); } return s; }}
使用HttpURLConnection进行网络请求
HttpURLConnection是URLConnection的子类,在URLConnection的基础上进一步改进增加了操作HTTP资源的便捷方法。
创建URL连接,发生请求,读取资源步骤与URLConnection基本一致。
区别
- 使用setRequestMethod()方法设置请求方式”GET”或者”POST”
- 使用getResponseCode()获取响应码,判断请求是否成功
- 可以使用disconnect()断开请求连接
HttpURLConnection实现GET与POST工具类
public class HttpConnectionUtil { public static HttpConnectionUtil http = new HttpConnectionUtil(); public static HttpConnectionUtil getHttp() { return http; } public String getRequset(final String url) { final StringBuilder sb = new StringBuilder(); FutureTask<String> task = new FutureTask<String>(new Callable<String>() { @Override public String call() throws Exception { HttpURLConnection connection = null; BufferedReader reader = null; try { URL requestUrl = new URL(url); connection = (HttpURLConnection) requestUrl.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); if (connection.getResponseCode() == 200) { InputStream in = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { sb.append(line); } System.out.println(sb); } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } if (connection != null) { connection.disconnect();//断开连接,释放资源 } } return sb.toString(); } }); new Thread(task).start(); String s = null; try { s = task.get(); } catch (Exception e) { e.printStackTrace(); } return s; } public String postRequset(final String url, final Map<String, String> map) { final StringBuilder sb = new StringBuilder(); FutureTask<String> task = new FutureTask<String>(new Callable<String>() { @Override public String call() throws Exception { HttpURLConnection connection = null; BufferedReader reader = null; try { URL requestUrl = new URL(url); connection = (HttpURLConnection) requestUrl.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(8000);//链接超时 connection.setReadTimeout(8000);//读取超时 //发送post请求必须设置 connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream out = new DataOutputStream(connection .getOutputStream()); StringBuilder request = new StringBuilder(); for (String key : map.keySet()) { request.append(key + "=" + URLEncoder.encode(map.get(key), "UTF-8") + "&"); } out.writeBytes(request.toString());//写入请求参数 out.flush(); out.close(); if (connection.getResponseCode() == 200) { InputStream in = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(in)); String line; while ((line = reader.readLine()) != null) { sb.append(line); } System.out.println(sb); } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { reader.close();//关闭流 } if (connection != null) { connection.disconnect();//断开连接,释放资源 } } return sb.toString(); } }); new Thread(task).start(); String s = null; try { s = task.get(); } catch (Exception e) { e.printStackTrace(); } return s; }}
运行测试
具体测试代码请下载查看,直接上效果图。
Demo Module项目下载
CSDN
http://download.csdn.net/detail/demonliuhui/9836919
GitHub
https://github.com/DeMonLiu623/StudyDemo/tree/master/AndroidNet
0 0
- Android 原生代码实现网络请求
- Android开发中的原生代码的网络访问和请求
- Android--使用原生技术实现ListView(原生技术实现网络异步请求,解析json数据)
- javascript原生代码实现ajax请求
- 原生JavaScript实现ajax异步请求代码
- Android 网络请求实现
- iOS-原生网络请求
- 网络请求原生
- IOS 原生网络请求
- iOS 原生网络请求
- iOS 原生网络请求
- Android网络请求代码封装
- Android 原生HttpURLConnection网络请求工具类(get post)
- Android联网app必用Get请求和Post请求的区别,网络编程代码实现
- android--原生http请求
- Android 实现网络请求单元测试
- iOS 原生网络请求写法
- iOS 原生网络请求封装
- 前台线程和后台线程
- 补c++第四次实验
- 相机获取不到返回数据
- 解读DockerCon_2017——阿里云专家的美国行记录与思考
- Android Canvas的save(),saveLayer()和restore()浅谈
- Android 原生代码实现网络请求
- Ios上传图片 后台接收
- Python环境安装
- 加强学习技术
- 消息队列:比较Beanstalkd,IronMQ和Amazon SQS
- Android Device Monitor中File Explorer无法查看文件
- hrbustoj 1681 回文串 [BIT]【字符串hash】
- Java面向对象设计模式(十八)——命令模式(Command)
- 问题