Android - HttpURLConnection parameters from Map<String, Object> via POST method

允我心安 提交于 2019-12-06 14:17:40

问题


It's Just Q&A. means just a Wiki Post. I searched a lot to make this happen. All are posting different kind of answers. I am successfully using this code now. So I'd like to share to all.

Your HttpURLConnection must be inside Async Task (doInBackground).

Steps:

  1. Setting up parameters in Map Function
  2. Building string in form: param=val&param2=val2
  3. Setting up HttpUrlConnection
  4. OutputStream is used to attach values.
  5. Reading response from server using InputStream

Set Parameters:

Map<String,Object> params = new LinkedHashMap<>();
params.put("tag", "sda");

try {
                StringBuilder postData = new StringBuilder();
                for (Map.Entry<String,Object> 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());
            }

来源:https://stackoverflow.com/questions/33448973/android-httpurlconnection-parameters-from-mapstring-object-via-post-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!