Android - 来自Map <string,object =“”>的HttpURLConnection参数通过POST方法

时间:2015-10-31 07:00:07

标签: java android post httpurlconnection

  

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

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

步骤:

  1. 在地图功能中设置参数
  2. 以表格形式构建字符串:param=val&param2=val2
  3. 设置HttpUrlConnection
  4. OutputStream用于附加值。
  5. 使用InputStream
  6. 从服务器读取响应

    设置参数:

    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());
                }
    

0 个答案:

没有答案