简体   繁体   中英

how to send data from an android app to a server in the post method?

i have been using this method which seems a little redundant. Anyway is there a better way or is there anything I'm doing wrong here? This is in doinbackground method inside my async task. I also some other coding techniques which name value pairs. Is that better?

String myurl = "http://X.X.X.X/register.php";


        String name = strings[0];
        String email = strings[1];
        String username = strings[2];
        String password = strings[3];
        try {
            URL url = new URL(myurl);
            HttpURLConnection huc = (HttpURLConnection)url.openConnection();
            huc.setRequestMethod("POST");
            huc.setDoOutput(true);
            huc.setDoInput(true);
            OutputStream os = huc.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
            String post_data = URLEncoder.encode("name","UTF-8")  + "=" +URLEncoder.encode(name,"UTF-8") + "&"+
                    URLEncoder.encode("email","UTF-8")  + "=" +URLEncoder.encode(email,"UTF-8") + "&"+
                    URLEncoder.encode("username","UTF-8")  + "=" +URLEncoder.encode(username,"UTF-8")+ "&"+
                    URLEncoder.encode("password","UTF-8")  + "=" +URLEncoder.encode(password,"UTF-8") ;
            bw.write(post_data);
            bw.flush();
            bw.close();
            os.close();
            InputStream is = huc.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
            String result="";
            String line="";
            while((line = br.readLine()) !=null)
            {
                result += line;
            }
            br.close();
            is.close();
            huc.disconnect();
            return result;
        }catch (Exception e)
        {
            e.printStackTrace();
        }

the code you are using is ok. But in fact, there are better ways to do the same thing. Try using volley. You just add it as dependency in graddle and use it. Here is a link to the official Android docs.

https://developer.android.com/training/volley/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM