package cn.lingban.commons.untils; import javax.net.ssl.*; import java.io.*; import java.net.*; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.GZIPInputStream; public class HttpUtils { private static final int TIMEOUT = 10000;// 10秒 protected static HttpURLConnection createHttpConnection(URI uri) throws Exception { URLConnection urlConnection = uri.toURL().openConnection(); if (uri.getScheme().equals("https")) { try { SSLContext sslContext = null; HostnameVerifier hostnameVerifier = null; if (sslContext == null) { sslContext = allowSSLContext(); } if (hostnameVerifier == null) { hostnameVerifier = createHostnameVerifier(); } HttpsURLConnection connection = (HttpsURLConnection) urlConnection; connection.setSSLSocketFactory(sslContext.getSocketFactory()); connection.setHostnameVerifier(hostnameVerifier); return connection; } catch (Exception e) { throw new Exception(e); } } else { return (HttpURLConnection) urlConnection; } } protected static HostnameVerifier createHostnameVerifier() { return new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; } public static SSLContext allowSSLContext() throws Exception { try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new X509TrustManager[] { createX509TrustManager() }, new java.security.SecureRandom()); return sslContext; } catch (NoSuchAlgorithmException e) { throw new Exception("Create SSLContext NoSuchAlgorithmException:", e); } catch (KeyManagementException e) { throw new Exception("Create SSLContext KeyManagementException:", e); } } protected static X509TrustManager createX509TrustManager() { return new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted( X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } @Override public void checkClientTrusted( X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException { } }; } protected static InputStream getInputStream(HttpURLConnection conn) throws Exception { if(conn == null) return null; // showHeader(conn); String contentEncoding = conn.getHeaderField("Content-Encoding"); if(contentEncoding != null && contentEncoding.contains("gzip")) { return new GZIPInputStream(conn.getInputStream()); } else { return conn.getInputStream(); } } /** * 传送文本,例如Json,xml等 */ public static String sendText(String urlPath, String txt) throws Exception { return sendText(urlPath, txt, "UTF-8", null); } public static String sendText(String urlPath, String txt, Map<String, String> headers) throws Exception { return sendText(urlPath, txt, "UTF-8", headers); } public static String sendText(String urlPath, String txt, String encoding) throws Exception { return sendText(urlPath, txt, encoding, null); } public static String sendText(String urlPath, String txt, String encoding, Map<String, String> headers) throws Exception { byte[] sendData = txt.getBytes(); HttpURLConnection conn = createHttpConnection(URI.create(urlPath)); conn.setRequestMethod("POST"); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); // 如果通过post提交数据,必须设置允许对外输出数据 conn.setDoOutput(true); if(headers != null) { Set<Map.Entry<String, String>> set = headers.entrySet(); for(Map.Entry<String, String> entry : set) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } } conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setRequestProperty("Charset", encoding); conn.setRequestProperty("Content-Length", String.valueOf(sendData.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(sendData); outStream.flush(); outStream.close(); if (conn.getResponseCode() == 200) { // 获得服务器响应的数据 // String responseData = ""; // byte[] b = IOUtils.toByteArray(new GZIPInputStream(conn.getInputStream())); /* System.out.println("长度========================" + b.length); responseData = new String(b);*/ BufferedReader in = new BufferedReader(new InputStreamReader(getInputStream(conn), encoding)); // 数据 String retData = null; String responseData = ""; while ((retData = in.readLine()) != null) { responseData += retData; } in.close(); return responseData; } else { printErrorMessage(conn); } return "sendText error!"; } /** * 上传文件 */ public static String sendFile(String urlPath, String filePath) throws Exception { return sendFile(urlPath, filePath, null, null); } public static String sendFile(String urlPath, String filePath, Map<String, String> headers) throws Exception { return sendFile(urlPath, filePath, null, headers); } public static String sendFile(String urlPath, String filePath, String newName) throws Exception { return sendFile(urlPath, filePath, newName, null); } public static String sendFile(String urlPath, String filePath, String newName, Map<String, String> headers) throws Exception { String end = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; File file = new File(filePath); HttpURLConnection con = createHttpConnection(URI.create(urlPath)); /* 允许Input、Output,不使用Cache */ con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); /* 设置传送的method=POST */ con.setRequestMethod("POST"); /* setRequestProperty */ if(headers != null) { Set<Map.Entry<String, String>> set = headers.entrySet(); for(Map.Entry<String, String> entry : set) { con.setRequestProperty(entry.getKey(), entry.getValue()); } } con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); /* 设置DataOutputStream */ DataOutputStream ds = new DataOutputStream(con.getOutputStream()); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\";filename=\"" + (newName == null ? file.getName() : newName) + "\"" + end); ds.writeBytes(end); /* 取得文件的FileInputStream */ FileInputStream fStream = new FileInputStream(file); /* 设置每次写入1024bytes */ int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = -1; /* 从文件读取数据至缓冲区 */ while ((length = fStream.read(buffer)) != -1) { /* 将资料写入DataOutputStream中 */ ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end); /* close streams */ fStream.close(); ds.flush(); if (con.getResponseCode() == 200) { /* 取得Response内容 */ InputStream is = getInputStream(con); StringBuffer b = new StringBuffer(); InputStreamReader inputStreamReader = new InputStreamReader(is, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { b.append(str); } /*StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); }*/ /* 关闭DataOutputStream */ ds.close(); return b.toString(); } else { printErrorMessage(con); return null; } } public static String httpRequest(String requestUrl, String requestMethod, String outputStr) { return httpsRequest(requestUrl, requestMethod, outputStr); } /** * 发起https请求并获取结果 * * @param requestUrl * 请求地址 * @param requestMethod * 请求方式(GET、POST) * @param outputStr * 提交的数据 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) */ public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) { String respStr = null; StringBuffer buffer = new StringBuffer(); try { HttpURLConnection httpUrlConn = createHttpConnection(URI.create(requestUrl)); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 设置请求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); httpUrlConn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8"); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // 当有数据需要提交时 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意编码格式,防止中文乱码 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 将返回的输入流转换成字符串 InputStream inputStream = getInputStream(httpUrlConn); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); respStr = buffer.toString(); // jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { System.out.println("server connection timed out."); } catch (Exception e) { System.out.println("https request error:{}" + e.getMessage()); e.printStackTrace(); } return respStr; } /** * 通过get方式提交参数给服务器 */ public static String sendGetRequest(String urlPath, Map<String, String> params) throws Exception { return sendGetRequest(urlPath, params, "UTF-8", null); } public static String sendGetRequest(String urlPath, Map<String, String> params, Map<String, String> headers) throws Exception { return sendGetRequest(urlPath, params, "UTF-8", headers); } public static String sendGetRequest(String urlPath, Map<String, String> params, String encoding) throws Exception { return sendGetRequest(urlPath, params, encoding, null); } public static String sendGetRequest(String urlPath, Map<String, String> params, String encoding, Map<String, String> headers) throws Exception { // 使用StringBuilder对象 StringBuilder sb = new StringBuilder(urlPath); if (params != null) { sb.append('?'); // 迭代Map for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), encoding)).append('&'); } sb.deleteCharAt(sb.length() - 1); } // 打开链接 HttpURLConnection conn = createHttpConnection(URI.create(sb.toString())); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "text/xml"); conn.setRequestProperty("Charset", encoding); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); if(headers != null) { Set<Map.Entry<String, String>> set = headers.entrySet(); for(Map.Entry<String, String> entry : set) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } } // 如果请求响应码是200,则表示成功 if (conn.getResponseCode() == 200) { // 获得服务器响应的数据 BufferedReader in = new BufferedReader(new InputStreamReader(getInputStream(conn), encoding)); // 数据 String retData = null; String responseData = ""; while ((retData = in.readLine()) != null) { responseData += retData; } in.close(); return responseData; } else { printErrorMessage(conn); } return "sendGetRequest error!"; } /** * 通过Post方式提交参数给服务器,也可以用来传送json或xml文件 */ public static String sendPostRequest(String urlPath, Map<String, String> params, String encoding) throws Exception { StringBuilder sb = new StringBuilder(); // 如果参数不为空 if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { // Post方式提交参数的话,不能省略内容类型与长度 sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), encoding)).append('&'); } sb.deleteCharAt(sb.length() - 1); } // 得到实体的二进制数据 byte[] entitydata = sb.toString().getBytes(); HttpURLConnection conn = createHttpConnection(URI.create(urlPath)); conn.setRequestMethod("POST"); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); // 如果通过post提交数据,必须设置允许对外输出数据 conn.setDoOutput(true); // 这里只设置内容类型与内容长度的头字段 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // conn.setRequestProperty("Content-Type", "text/xml"); conn.setRequestProperty("Charset", encoding); conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length)); OutputStream outStream = conn.getOutputStream(); // 把实体数据写入是输出流 outStream.write(entitydata); // 内存中的数据刷入 outStream.flush(); outStream.close(); // 如果请求响应码是200,则表示成功 if (conn.getResponseCode() == 200) { // 获得服务器响应的数据 BufferedReader in = new BufferedReader(new InputStreamReader(getInputStream(conn), encoding)); // 数据 String retData = null; String responseData = ""; while ((retData = in.readLine()) != null) { responseData += retData; } in.close(); return responseData; } else { printErrorMessage(conn); } return "sendText error!"; } /** * 根据URL直接读文件内容,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容 */ public static String readTxtFile(String urlStr, String encoding) throws Exception { StringBuffer sb = new StringBuffer(); String line = null; BufferedReader buffer = null; try { // 创建一个URL对象 // 创建一个Http连接 HttpURLConnection urlConn = createHttpConnection(URI.create(urlStr)); // 使用IO流读取数据 buffer = new BufferedReader(new InputStreamReader(getInputStream(urlConn), encoding)); while ((line = buffer.readLine()) != null) { sb.append(line); } } catch (Exception e) { throw e; } finally { try { buffer.close(); } catch (Exception e) { e.printStackTrace(); } } return sb.toString(); } /** * 该函数返回整形 -1:代表下载文件出错 0:代表下载文件成功 1:代表文件已经存在 */ public static int downloadFile(String urlStr, String path, String fileName) throws Exception { InputStream inputStream = null; try { inputStream = getInputStreamFromUrl(urlStr); File resultFile = write2FileFromInput(path, fileName, inputStream); if (resultFile == null) { return -1; } } catch (Exception e) { return -1; } finally { try { inputStream.close(); } catch (Exception e) { throw e; } } return 0; } /** * 根据URL得到输入流 * * @param urlStr * @return * @throws MalformedURLException * @throws IOException */ public static InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException, IOException { HttpURLConnection urlConn = null; try { urlConn = createHttpConnection(URI.create(urlStr)); } catch (Exception e) { e.printStackTrace(); } InputStream inputStream = urlConn.getInputStream(); return inputStream; } /** * 将一个InputStream里面的数据写入到SD卡中 */ private static File write2FileFromInput(String directory, String fileName, InputStream input) { File file = null; String tmpPath = System.getProperty("java.io.tmpdir"); FileOutputStream output = null; File dir = new File(tmpPath + directory); if (!dir.exists()) { dir.mkdir(); } try { file = new File(dir + File.separator + fileName); file.createNewFile(); output = new FileOutputStream(file); byte buffer[] = new byte[1024]; while ((input.read(buffer)) != -1) { output.write(buffer); } output.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } return file; } public static void printErrorMessage(HttpURLConnection conn) throws Exception { showHeader(conn); /*List<String> server = map.get("Server"); if (server == null) { System.out.println("Key 'Server' is not found!"); } else { for (String values : server) { System.out.println(values); } }*/ BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); // 数据 String retData = null; String responseData = ""; while ((retData = in.readLine()) != null) { responseData += retData; } in.close(); System.out.println(responseData); } public static void showHeader(HttpURLConnection conn) { Map<String, List<String>> map = conn.getHeaderFields(); System.out.println("显示响应Header信息"); for (Map.Entry<String, List<String>> entry : map.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } System.out.println("使用key获得响应Header信息"); } }
相关推荐
**Android-OkHttp3.0网络工具类** 在Android应用开发中,网络请求是不可或缺的一部分。OkHttp3.0是一个高效、易用的网络通信库,由Square公司开发,广泛应用于Android项目中。相较于旧版本,OkHttp3带来了许多性能...
安卓网络工具类,开机检查网络状态,是否有网,wifi,还是手机网络。
一个处理网络请求的工具类,较全面的包含了网络的请求处理,移动开发必备的一款工具
Android 网络工具类详解 Android 网络工具类是 Android 开发中不可或缺的一部分,对于 Android 应用程序的网络连接和数据传输起着至关重要的作用。在 Android 中,网络工具类通常用于判断网络状态、获取当前网络...
写在前面: Retrofit与okhttp共同出自于Square公司,是目前市场上使用最多的联网框架,retrofit是对okhttp做了一层封装,不过封装之后的retrofit上手还是极其复杂,为了解决使用难度问题,本文推荐使用github开源项目...
打开网络设置界面,获取活动网络信息,判断网络是否可用,判断网络是否是4G,判断wifi是否连接状态,获取移动网络运营商名称,获取当前的网络类型,获取当前的网络类型(WIFI,2G,3G,4G)
捕获异常、存sd卡、自定义封装json(含网络工具类)、生成Json格式、传log日志到服务器、app崩溃友好重启 http://blog.csdn.net/u013210620/article/details/51917266
1. **初始化网络工具类**:首先,你需要在项目中引入"LCNetWorking"的头文件,并创建其实例。 ```objc #import "LCNetWorking.h" LCNetWorking *netManager = [LCNetWorking sharedInstance]; ``` 2. **发起GET...
8. **网络通信**:网络工具类可能包含URL编码解码、HTTP请求发送等功能,为网络编程提供便利。 9. **异常处理**:提供统一的异常处理方法,如`ExceptionUtils.printStackTrace()`,可以在捕获异常时打印堆栈跟踪,...
2. **网络工具类**:可能包含了网络请求的辅助方法,如`HttpUtils`,可以方便地进行GET、POST请求,或者处理网络异常。 3. **文件操作类**:如`FileUtils`,可能会提供读写文件、压缩解压、资源文件操作等方法。 4...
9. **网络工具类(NetworkUtil)**:这类工具类通常用于处理网络相关的操作,如获取IP地址、检查网络连接等。例如`getLocalHostIp()`获取本地主机的IP地址,`isNetworkAvailable()`检查网络是否可用。 10. **JSON处理...
6. **网络工具类**: 可能包括URL的打开、HTTP请求的发送、网络数据的下载等功能。例如,`HttpUtils`可以方便地处理HTTP请求,而`SocketUtils`则简化了套接字操作。 7. **线程和并发工具类**: 提供了线程的创建、...
网络工具类则可能帮助我们简化HTTP请求或处理网络数据。 在实际开发中,这样的工具类库非常有价值,因为它们可以帮助我们避免重复造轮子,专注于核心业务逻辑。此外,通过阅读和学习这些工具类的源码,开发者还可以...
- Android开发中常见的工具类包括:字符串工具类(处理字符串格式化、拼接等)、日期时间工具类(格式化日期和时间)、网络工具类(检查网络状态、发起网络请求)、图片处理工具类(裁剪、压缩、加载图片)等。...
7. **网络工具类**:如NetUtils,可以用来检查网络连接状态、获取IP地址等,有助于网络相关的功能实现。 8. **反射工具类**:如ReflectionUtils,通过反射机制,可以动态访问类、字段、方法,增强了代码的灵活性。 ...
5. **网络通信**:网络工具类可能包含HTTP请求、TCP/UDP通信、数据序列化与反序列化等,方便进行网络编程。 6. **数据验证**:这些工具类可能提供输入验证,如邮箱格式检查、手机号码合法性验证、身份证号校验等,...
6. **示例代码和文档**:为了方便开发者使用,项目可能还包括了示例代码和详细的使用文档,指导如何集成和调用这些网络工具。 在实际开发中,网络状态管理是不可或缺的一部分,尤其是在设计需要频繁与服务器交互的...
6. **网络工具类**:支持HTTP/HTTPS请求,可以进行数据的上传和下载,同时提供了异步处理机制,避免阻塞主线程。 7. **图片工具类**:包括图片的压缩、裁剪、加载等功能,对于处理图片资源非常实用。 8. **权限...
10. **网络工具类**:网络工具类可能包含URL编码解码、HTTP请求头管理、JSON解析等功能,简化网络数据的获取和处理。 11. **线程池工具类**:在Android中,合理管理线程池可以提高性能和避免内存泄漏。这类工具类...
3. **网络工具类**:在网络编程中,这类工具类用于处理HTTP请求、URL解析、网络连接等任务。例如,`HttpURLConnection`和`OkHttp`在Java和Android开发中广泛使用,提供便捷的网络请求功能。 4. **数据序列化与反...