HttpURLConnection实现网络请求
来源:互联网 发布:5.x unity3d 粒子系统 编辑:程序博客网 时间:2024/05/16 08:41
自从Android5.x时代google将Apache抛弃之后,HttpURLConnection变成了Android系统默认的请求方式.两者的区别在于:
1、标准Java接口(java.net) —-HttpURLConnection,可以实现简单的基于URL请求、响应功能;
2、Apache接口(org.appache.http)—-HttpClient,使用起来更方面更强大。一般来说,用这种接口。不过本文还是把第一种接口过一下。
任何一种接口,无外乎四个基本功能:访问网页、下载图片或文件、上传文件,访问接口获取数据,根据URL请求的类别: 分为二类,GET与POST请求。
二者的区别在于:
a:) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
据此,写了一个小小的工具类
/** * Created by xuenan on 2016/9/22 0022. */import android.util.Log;import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import java.util.HashMap;/** * 创建的HttpURLConection的工具类 */public class HttpUtil2 { //把Cookie定义为静态变量,第一次获取之后保存起来,以后每一次请求都设置给请求头即可 public static String COOKIE = ""; //GET请求实现 public static String RequetstGet(String baseUrl, HashMap<String, String> paramsMap) { try { StringBuilder tempParams = new StringBuilder(); int pos = 0; for (String key : paramsMap.keySet()) { if (pos > 0) { tempParams.append("&"); } tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8"))); pos++; } String requestUrl = baseUrl + tempParams.toString(); // 新建一个URL对象 URL url = new URL(requestUrl); // 打开一个HttpURLConnection连接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 设置连接主机超时时间 urlConn.setConnectTimeout(5 * 1000); //设置从主机读取数据超时 urlConn.setReadTimeout(5 * 1000); // 设置是否使用缓存 默认是true urlConn.setUseCaches(true); // 设置为Post请求 urlConn.setRequestMethod("GET"); //urlConn设置请求头信息 //设置请求中的媒体类型信息。 urlConn.setRequestProperty("Content-Type", "application/json"); //设置客户端与服务连接类型 urlConn.addRequestProperty("Connection", "Keep-Alive"); // 开始连接 urlConn.connect(); // 判断请求是否成功 if (urlConn.getResponseCode() == 200) { // 获取返回的数据 可以选择流 字节 字符串三种 String result = streamToString(urlConn.getInputStream()); return result; } else { Log.e("TAG", "Get方式请求失败"); } // 关闭连接 urlConn.disconnect(); } catch (Exception e) { Log.e("TAG", e.toString()); } return null; } //POST请求实现 private String requestPost(String baseUrl, HashMap<String, String> paramsMap) { try { //合成参数 StringBuilder tempParams = new StringBuilder(); int pos = 0; for (String key : paramsMap.keySet()) { if (pos > 0) { tempParams.append("&"); } tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8"))); pos++; } String params = tempParams.toString(); // 请求的参数转换为byte数组 byte[] postData = params.getBytes(); // 新建一个URL对象 URL url = new URL(baseUrl); // 打开一个HttpURLConnection连接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 设置连接超时时间 urlConn.setConnectTimeout(5 * 1000); //设置从主机读取数据超时 urlConn.setReadTimeout(5 * 1000); // Post请求必须设置允许输出 默认false urlConn.setDoOutput(true); //设置请求允许输入 默认是true urlConn.setDoInput(true); // Post请求不能使用缓存 urlConn.setUseCaches(false); // 设置为Post请求 urlConn.setRequestMethod("POST"); //将获取的Cookie存入请求头中发给服务器,如果服务器需要Cookie请求头的话 //urlConn.setRequestProperty("Cookie", COOKIE); //设置本次连接是否自动处理重定向 urlConn.setInstanceFollowRedirects(true); //获取返回的cookie的map集合 //Map<String,List<String>> cookieMap = urlConn.getHeaderFields(); //获取后台返回的特定的cookie 这个cookie也可以由后台作为返回值返给前台,然后前台保存调用 //获取Cookie:从返回的消息头里的Set-Cookie的相应的值 //COOKIE = urlConn.getHeaderField("Set-Cookie"); // 配置请求Content-Type urlConn.setRequestProperty("Content-Type", "application/json"); // 开始连接 urlConn.connect(); // 发送请求参数 DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream()); dos.write(postData); dos.flush(); dos.close(); // 判断请求是否成功 if (urlConn.getResponseCode() == 200) { // 获取返回的数据 String result = streamToString(urlConn.getInputStream()); return result; } else { Log.e("TAG", "Post方式请求失败"); } // 关闭连接 urlConn.disconnect(); } catch (Exception e) { Log.e("TAG", e.toString()); } return null; } //处理网络流:将输入流转换成字符串 /** * 将输入流转换成字符串 * * @param is 从网络获取的输入流 * @return */ public static String streamToString(InputStream is) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } baos.close(); is.close(); byte[] byteArray = baos.toByteArray(); return new String(byteArray); } catch (Exception e) { Log.e("TAG", e.toString()); return null; } finally { try { if (is != null) { is.close(); } if (baos != null) { baos.close(); } } catch (IOException e) { e.printStackTrace(); } } } //文件下载 public static void downloadFile(String fileUrl) { FileOutputStream fos = null; InputStream inputStream = null; try { // 新建一个URL对象 URL url = new URL(fileUrl); // 打开一个HttpURLConnection连接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 设置连接主机超时时间 urlConn.setConnectTimeout(5 * 1000); //设置从主机读取数据超时 urlConn.setReadTimeout(5 * 1000); // 设置是否使用缓存 默认是true urlConn.setUseCaches(true); // 设置为Post请求 urlConn.setRequestMethod("GET"); //urlConn设置请求头信息 //设置请求中的媒体类型信息。 urlConn.setRequestProperty("Content-Type", "application/json"); //设置客户端与服务连接类型 urlConn.addRequestProperty("Connection", "Keep-Alive"); // 开始连接 urlConn.connect(); // 判断请求是否成功 if (urlConn.getResponseCode() == 200) { String filePath = ""; File descFile = new File(filePath); fos = new FileOutputStream(descFile); byte[] buffer = new byte[1024]; int len; inputStream = urlConn.getInputStream(); while ((len = inputStream.read(buffer)) != -1) { // 写到本地 fos.write(buffer, 0, len); } } else { Log.e("TAG", "文件下载失败"); } // 关闭连接 urlConn.disconnect(); } catch (Exception e) { Log.e("TAG", e.toString()); } finally { try { if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } //文件上传 public static void upLoadFile(String filePath, HashMap<String, String> paramsMap) { DataInputStream in = null; FileInputStream fileInput = null; DataOutputStream requestStream = null; try { String baseUrl = "https://xxx.com/uploadFile"; File file = new File(filePath); //新建url对象 URL url = new URL(baseUrl); //通过HttpURLConnection对象,向网络地址发送请求 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); //设置该连接允许读取 urlConn.setDoOutput(true); //设置该连接允许写入 urlConn.setDoInput(true); //设置不能适用缓存 urlConn.setUseCaches(false); //设置连接超时时间 urlConn.setConnectTimeout(5 * 1000); //设置连接超时时间 //设置读取超时时间 urlConn.setReadTimeout(5 * 1000); //读取超时 //设置连接方法post urlConn.setRequestMethod("POST"); //设置维持长连接 urlConn.setRequestProperty("connection", "Keep-Alive"); //设置文件字符集 urlConn.setRequestProperty("Accept-Charset", "UTF-8"); //设置文件类型 urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "*****"); String name = file.getName(); requestStream = new DataOutputStream(urlConn.getOutputStream()); requestStream.writeBytes("--" + "*****" + "\r\n"); //发送文件参数信息 StringBuilder tempParams = new StringBuilder(); tempParams.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + name + "\"; "); int pos = 0; int size = paramsMap.size(); for (String key : paramsMap.keySet()) { tempParams.append(String.format("%s=\"%s\"", key, paramsMap.get(key), "utf-8")); if (pos < size - 1) { tempParams.append("; "); } pos++; } tempParams.append("\r\n"); tempParams.append("Content-Type: application/octet-stream\r\n"); tempParams.append("\r\n"); String params = tempParams.toString(); requestStream.writeBytes(params); //发送文件数据 fileInput = new FileInputStream(file); int bytesRead; byte[] buffer = new byte[1024]; in = new DataInputStream(new FileInputStream(file)); while ((bytesRead = in.read(buffer)) != -1) { requestStream.write(buffer, 0, bytesRead); } requestStream.writeBytes("\r\n"); requestStream.flush(); requestStream.writeBytes("--" + "*****" + "--" + "\r\n"); requestStream.flush(); fileInput.close(); int statusCode = urlConn.getResponseCode(); if (statusCode == 200) { // 获取返回的数据 String result = streamToString(urlConn.getInputStream()); } else { Log.e("TAG", "上传失败"); } } catch (IOException e) { Log.e("TAG", e.toString()); } finally { try { if (in != null) { in.close(); } if (fileInput != null) { fileInput.close(); } if (requestStream != null) { requestStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }}
再附一个json解析工具类
package com.xuenan.aaa;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.TypeReference;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/** * </br> * Created in 2016-11-26 * * @author zhuangxuenan */public class JsonUtil { /** * 用fastjson 将json字符串解析为一个 JavaBean * * @param jsonString * @param cls * @return */ public static <T> T parseJson(String jsonString, Class<T> cls) { T t = null; try { t = JSON.parseObject(jsonString, cls); } catch (Throwable e) { e.printStackTrace(); } return t; } /** * 用fastjson 将json字符串 解析成为一个 List<JavaBean> 及 List<String> * * @param jsonString * @param cls * @return */ public static <T> List<T> parseJsonList(String jsonString, Class<T> cls) { List<T> list = new ArrayList<T>(); try { List<T> tempList = JSON.parseArray(jsonString, cls); if (tempList != null) list.addAll(tempList); } catch (Exception e) { } return list; } /** * 用fastjson 将jsonString 解析成 List<Map<String,Object>> * * @param jsonString * @return */ public static List<Map<String, Object>> parseJsonListMap(String jsonString) { List<Map<String, Object>> list = new ArrayList<>(); try { // 两种写法 // list = JSON.parseObject(jsonString, new // TypeReference<List<Map<String, Object>>>(){}.getType()); List<Map<String, Object>> tempList = JSON.parseObject(jsonString, new TypeReference<List<Map<String, Object>>>() { }); if (tempList != null) list.addAll(tempList); } catch (Exception e) { e.printStackTrace(); } return list; } /** * 解析为Map */ public static Map<String, Object> parseJsonMap(String jsonString) { Map<String, Object> map = new HashMap<>(); try { // 两种写法 // list = JSON.parseObject(jsonString, new // TypeReference<List<Map<String, Object>>>(){}.getType()); Map<String, Object> tempMap = JSON.parseObject(jsonString, new TypeReference<Map<String, Object>>() { }); if (tempMap != null) map.putAll(tempMap); } catch (Exception e) { e.printStackTrace(); } return map; }}
0 0
- HttpURLConnection实现网络请求
- 请求网络之HttpUrlConnection
- HttpURLConnection请求网络
- HttpURLConnection 网络请求数据
- HttpURLConnection+URl网络请求
- HttpURLConnection网络请求
- HttpURLConnection网络请求
- HttpUrlConnection网络请求
- HttpURLConnection请求网络
- URLConnection &HttpURLConnection 网络请求
- HttpURLConnection 请求网络
- HttpURLConnection、HttpClient网络请求
- HttpURLConnection网络请求
- HttpURLConnection---网络请求数据
- 转发请求实现HttpURLConnection
- HttpUrlConnection 网络请求工具类
- HttpURLConnection请求网络小练习
- android HttpURLConnection网络请求数据
- APICloud webstorm本地打包 apk出不来的问题
- (进程编程)共享内存总结(笔记整理)
- Ural1395&&Ural1452——Pascal vs. C++
- Mef
- Sublime Text 3使用SublimeLinter配置JS,CSS,HTML语法检查
- HttpURLConnection实现网络请求
- Linux学习笔记3——设置用户ID和设置组ID
- 为什么要重写hashcode()方法
- Leetcode349. Intersection of Two Arrays
- PacketiX VPN 搭建企业VPN服务器
- 两个blcok的使用问题
- Socket心跳包机制
- 关于护肤那点事
- LA4670 Dominating Patterns(AC自动机)