/** * * @param urlStr * url * @param content * 提交的參數 * @param encoding * 編碼格式 * @return */ public static String getUrlResult(String urlStr, Map<String,Object> map,String method) { URL url = null; HttpURLConnection connection = null; try { url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection();// 新建連接實例 connection.setConnectTimeout(10000);// 設置連接超時時間,單位毫秒 connection.setReadTimeout(10000);// 設置讀取數據超時時間,單位毫秒 connection.setDoOutput(true);// 是否打開輸出流 true|false connection.setDoInput(true);// 是否打開輸入流true|false connection.setRequestMethod(method);// 提交方法POST|GET connection.setUseCaches(false);// 是否緩存true|false connection.connect();// 打開連接端口 DataOutputStream out = new DataOutputStream( connection.getOutputStream());// 打開輸出流往對端服務器寫數據 String content=buildUrlQuery(map); out.writeBytes(content);// 寫數據,也就是提交你的表單 name=xxx&pwd=xxx out.flush();// 刷新 out.close();// 關閉輸出流 BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream(), "UTF-8"));// 往對端寫完數據對端服務器返回數據 // ,以BufferedReader流來讀取 StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); return buffer.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect();// 關閉連接 } } return ""; } private static String buildUrlQuery(Map<String, Object> querys) throws UnsupportedEncodingException { StringBuilder sbQuery = new StringBuilder(); if (null != querys) { for (Map.Entry<String, Object> query : querys.entrySet()) { if (0 < sbQuery.length()) { sbQuery.append("&"); } if (String.valueOf((query.getKey())).equals("null") && !String.valueOf((query.getValue().toString())).equals("null")) { sbQuery.append(query.getValue()); } if (!String.valueOf((query.getKey())).equals("null")) { sbQuery.append(query.getKey()); if (!String.valueOf(query.getValue()).equals("null")) { sbQuery.append("="); sbQuery.append(URLEncoder.encode(query.getValue().toString(), "utf-8")); } } } } return sbQuery.toString(); }