Android 发送带有参数的HTTP POST请求
示例
使用HashMap存储应通过POST参数发送给服务器的参数:
HashMap<String, String> params;
一旦paramsHashMap的填充,创建将用于它们发送到服务器StringBuilder的:
StringBuilder sbParams = new StringBuilder(); int i = 0; for (String key : params.keySet()) { try { if (i != 0){ sbParams.append("&"); } sbParams.append(key).append("=") .append(URLEncoder.encode(params.get(key), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } i++; }
然后,创建HttpURLConnection,打开连接,并发送POST参数:
try{ String url = "http://www.example.com/test.php"; URL urlObj = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.connect(); String paramsString = sbParams.toString(); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(paramsString); wr.flush(); wr.close(); } catch (IOException e) { e.printStackTrace(); }
然后收到服务器发回的结果:
try { InputStream in = new BufferedInputStream(conn.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } Log.d("test", "来自服务器的结果: " + result.toString()); } catch (IOException e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } }