版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33781658/article/details/83345717
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; // } // //}