008-HttpUrlConnection的get請求和post請求
阿新 • • 發佈:2018-11-07
HttpUrlConnection的get請求和post請求
的簡單標準請求方式
以後方便使用
---GET---
// HashMap<String, Object> params = new HashMap<>(); // params.put("name", "abc"); // params.put("age", "123"); // String baseUrl = UrlUtil.appendUrl("http://japi.juhe.cn/qqevaluate/qq", params); // // HttpURLConnection connection = null; // // try { // URL url = new URL(baseUrl); // connection = (HttpURLConnection) url.openConnection(); // connection.setRequestMethod("GET"); // connection.setConnectTimeout(5000); // connection.setReadTimeout(5000); // connection.connect(); // // String response = StreamUtil.getStringFromStream(connection.getInputStream()); // String result = response; // // } catch (Exception e) { // e.printStackTrace(); // } finally { // if (connection != null) { // connection.disconnect(); // } // }
---POST---
// HashMap<String, String> params = new HashMap<>(); // params.put("name", "abc"); // params.put("age", "123"); // String param = MapUtil.getStringFromMap(params); // // HttpURLConnection connection = null; // // try { // URL url = new URL("http://japi.juhe.cn/qqevaluate/qq"); // connection = (HttpURLConnection) url.openConnection(); // connection.setRequestMethod("POST"); // connection.setConnectTimeout(5000); // connection.setReadTimeout(5000); // // connection.connect(); // // PrintWriter writer = new PrintWriter(connection.getOutputStream()); // writer.write(param); // writer.flush(); // writer.close(); // // String response = StreamUtil.getStringFromStream(connection.getInputStream()); // // } catch (Exception e) { // e.printStackTrace(); // } finally { // if (connection != null) { // connection.disconnect(); // } // }
另外post引數拼接後寫入流
//public class MapUtil { // // public static String getStringFromMap(Map<String, String> map) { // String string = ""; // Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator(); // while (iterator.hasNext()) { // Map.Entry<String, String> entry = iterator.next(); // string = string + entry.getKey() + "=" + entry.getValue(); // if (iterator.hasNext()) { // string = string + "&"; // } // } // return string; // } // //}