import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Message; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.net.ssl.HttpsURLConnection; /** * Created by ios13 on 17/9/19. */ public class HttpURLConnectionUtil { /** * 通过get获取到远程数据 * * @param urlStr url链接地址 * @return * @throws Exception */ public static String getHttp(String urlStr) throws Exception { //String param1 = URLEncoder.encode(urlStr);//中文会进行url编码 StringBuffer response = null; URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //conn.setRequestMethod("GET"); //GET 表示希望从服务器那里获取数据 //POST 则表示希望提交数据给服务器 conn.setConnectTimeout(8000);//连接超时 conn.setReadTimeout(8000);//读取超时 //conn.connect(); if (conn.getResponseCode() == 200) { //成功 InputStream inStream = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); response = new StringBuffer(); while (reader.readLine() != null) { response.append(reader.readLine()); } } if (conn != null) { conn.disconnect(); } return response == null ? null : response.toString(); } private String getHttps(String urlStr) throws Exception { StringBuffer response = null; URL url = new URL(urlStr); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); //conn.setRequestMethod("GET"); //GET 表示希望从服务器那里获取数据 //POST 则表示希望提交数据给服务器 conn.setConnectTimeout(8000);//连接超时 conn.setReadTimeout(8000);//读取超时 //conn.connect(); if (conn.getResponseCode() == 200) { //成功 InputStream inStream = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); response = new StringBuffer(); while (reader.readLine() != null) { response.append(reader.readLine()); } } if (conn != null) { conn.disconnect(); } return response == null ? null : response.toString(); } /** * 通过post获取远程数据 * * @param urlStr url链接地址 * @param path 传递参数,xxx=xxx&aaa=bbb * @return * @throws Exception */ public static String postHttp(String urlStr, String path) throws Exception { // String urlStrs = URLEncoder.encode(urlStr); StringBuffer response = null; //String paths = URLEncoder.encode(path); URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(8000);//连接超时 conn.setReadTimeout(8000);//读取超时 DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(path); if (conn.getResponseCode() == 200) { //成功 InputStream inStream = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); response = new StringBuffer(); while (reader.readLine() != null) { response.append(reader.readLine()); } } if (conn != null) { conn.disconnect(); } return response == null ? null : response.toString(); } /** * 获取远程数据 * * @param url Url地址,如果传参数则直接放在后面,方法如同get请求 * @param methed 请求方式 post/get * @return */ public static String getHttpData(final String url, final String methed) { final String[] result = new String[1]; Thread thread= new Thread(new Runnable() { @Override public void run() { String obj = null; try { if (methed.toLowerCase().equals("post")) { String[] arry = url.split("\\?"); if (arry.length == 2) { //有参数 obj = postHttp(arry[0], arry[1]); } else if (arry.length == 1) { //无参数 obj = postHttp(arry[0], ""); } else { //存在错误 } } if (methed.toLowerCase().equals("get")) { obj = getHttp(url); } } catch (Exception e) { e.printStackTrace(); } result[0] = obj; } }); thread.start(); boolean bool=true; while (thread.isAlive()) { bool = thread.isAlive(); if (!thread.isAlive()) { break; } } return result[0]; } /** * 获取远程数据 * * @param url Url地址,如果传参数则直接放在后面,方法如同get请求 * @param methed 请求方式 post/get * @param handler Handler * 调用例子 * Handler hand=new Handler(){ * @Override public void handleMessage(Message msg) { * while (msg.what==1000001200){ * String result=msg.obj.toString(); * } * //这个result就是获取到的数据了 * super.handleMessage(msg); * } * }; * HttpURLConnectionUtil.getHttpThread("https://www.baidu.com","get", hand); */ public static void getHttpThread(final String url, final String methed, final Handler handler) { new Thread(new Runnable() { @Override public void run() { Message msg = new Message(); String obj = null; try { if (methed.toLowerCase().equals("post")) { String[] arry = url.split("\\?"); if (arry.length == 2) { //有参数 obj = postHttp(arry[0], arry[1]); } else if (arry.length == 1) { //无参数 obj = postHttp(arry[0], ""); } else { //存在错误 } } if (methed.toLowerCase().equals("get")) { obj = getHttp(url); } } catch (Exception e) { e.printStackTrace(); } msg.what = 1000001200; msg.obj = obj; //msg.sendToTarget(); handler.sendMessage(msg); } }).start(); // thread.currentThread().interrupt(); } /** * 获取远程数据 * * @param url url链接地址 * @param map 参数设置 * @param method 请求方式 * @param handler Handler 参照getHttpThread(final String url, final String methed, final Handler handler) */ public static void getHttpThreadByMap(String url, Map<String, Object> map, String method, Handler handler) { if (map.size() > 0) { url += "?"; Iterator it = map.keySet().iterator(); while (it.hasNext()) { String key = it.next().toString(); String value = map.get(key).toString(); url += key + "=" + value + "&"; } String lastStr = url.substring(url.length() - 1, url.length()); if (lastStr.equals("&")) { url = url.substring(0, url.length() - 1); } } getHttpThread(url, method, handler); } /** * 通过javabean获取数据 * @param url url链接地址 * @param bean javaben * @param method 请求方式 * @param beanIsNull 是否忽略空值的bean作为参数 * @param handler Handler 参照getHttpThread(final String url, final String methed, final Handler handler) * @throws Exception */ public static void getHttpThreadByBean(String url, Object bean, String method, boolean beanIsNull, Handler handler) throws Exception { Map<String, Object> map =new HashMap<>(); if (beanIsNull == true) {//忽略掉参数是null的 map = BeanToMapNotNull(bean); } else { map = BeanToMap(bean); } getHttpThreadByMap(url, map, method, handler); } /** * 通过图片远程地址获取图片 * @param ImgPath 图片地址 * @return * @throws Exception */ public static Bitmap getImg(final String ImgPath) throws Exception { final Bitmap[] bt = new Bitmap[1]; Thread thread=new Thread(new Runnable() { @Override public void run() { try { URL url = new URL(ImgPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); //GET 表示希望从服务器那里获取数据 //POST 则表示希望提交数据给服务器 conn.setConnectTimeout(8000);//连接超时 conn.setReadTimeout(8000);//读取超时 InputStream in = conn.getInputStream(); bt[0] = BitmapFactory.decodeStream(in); }catch (Exception e){ e.printStackTrace(); } } }); thread.start(); boolean bool=true; while (thread.isAlive()) { //这个循环会一直到这个进程结束 bool = thread.isAlive(); if (!thread.isAlive()) { break; } } return bt[0]; } /** * bean转map 空值不忽略static * * @param obj bean * @return * @throws Exception */ private static Map<String, Object> BeanToMap(Object obj) throws Exception { Field[] fields = obj.getClass().getDeclaredFields(); Map<String, Object> map = new HashMap(); for (Field field : fields) { //String type=fields[i].getType().toString(); String name = field.getName(); if (!name.equals("serialVersionUID") && !name.equals("$change")) { // 获取属性的名字 // 将属性的首字符大写,方便构造get,set方法 name = name.substring(0, 1).toUpperCase() + name.substring(1); // 获取属性的类型 String type = field.getGenericType().toString(); Method m = obj.getClass().getMethod("get" + name); // 调用getter方法获取属性值 Object value = m.invoke(obj); map.put(field.getName(), value); } } return map; } /** * bean转map 空值忽略static * * @param obj bean * @return * @throws Exception */ private static Map<String, Object> BeanToMapNotNull(Object obj) throws Exception { Field[] fields = obj.getClass().getDeclaredFields(); Map<String, Object> map = new HashMap(); for (Field field : fields) { //String type=fields[i].getType().toString(); String name = field.getName(); if (!name.equals("serialVersionUID") && !name.equals("$change")) { // 获取属性的名字 // 将属性的首字符大写,方便构造get,set方法 name = name.substring(0, 1).toUpperCase() + name.substring(1); // 获取属性的类型 String type = field.getGenericType().toString(); Method m = obj.getClass().getMethod("get" + name); // 调用getter方法获取属性值 Object value = m.invoke(obj); if (value != null) { map.put(field.getName(), value); } } } return map; } }
//新手上路,请多多指教