Android – 来自Map 的HttpURLConnection参数通过POST方法

这只是问答。 仅仅意味着一个维基百科。 我经常搜索以实现这一目标。 所有人都发布了不同类型的答案。 我现在成功使用此代码。 所以我想与所有人分享。

您的HttpURLConnection必须位于异步任务(doInBackground)中。

脚步:

  1. 在Map Function中设置参数
  2. 在表单中构建字符串: param=val&param2=val2
  3. 设置HttpUrlConnection
  4. OutputStream用于OutputStream
  5. 使用InputStream从服务器读取响应

设置参数:

 Map params = new LinkedHashMap(); params.put("tag", "sda"); try { StringBuilder postData = new StringBuilder(); for (Map.Entry param : params.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(URLEncoder.encode(param.getKey(), "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")); } String postdata = postData.toString(); Log.w("postData", postdata); //HERE Postdata will be 'param=val' byte[] postDataBytes = postData.toString().getBytes(); //NOW, Establishes HttpConnection URL url = new URL(config.URL_REGISTER); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.getOutputStream().write(postDataBytes); //Read the Response from Server. I use echo json_encode($response); in php file. where $response["key"] = $value; BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); Log.e("connec()", "UnsupportedEncodingException: " + e.toString()); } catch (ProtocolException e) { e.printStackTrace(); Log.e("connec()", "ProtocolException: " + e.toString()); } catch (IOException e) { e.printStackTrace(); Log.e("connec()", "IOException: " + e.toString()); }