Android development-WEB access (POST) Try to communicate with the outside and send data. ~

Introduction

Hello. I'm Wataku, a server-side programmer who is studying programming at a certain school. : relaxed: Let's develop Android this time as well. This time I would like to connect to an external network with Android and send data. It's almost the same as the last GET.

Target person

--A person who can write java reasonably. --A person who can do so in Android development. -Android development-WEB access (GET) Try to get data by communicating with the outside. ~.

POST transmission

  1. Prepare a character string that connects the request parameters to be sent with "&".
String postData =“Request parameter 1= ” +Value 1+ “ &Request parameter 2= ” +Value 2
  1. Set the request method to POST.
con.setRequestMethod(“POST”)
  1. Enables output of request parameters.
con.setDoOutput(true)
  1. Get OutputStream. → Connect the server and the pipe.
OutputStream os = con.getOutputStream()
  1. Send request parameters → Connect the server and pipe.
os.write(postData.getByte())
//String(String)Data cannot be sent unless it is converted to bytes

** (Note) ** * Con.connect () is not required for POST. * Progress When ** publishProgress () ** is called in "doInBackground ()" of AsyucTask, "onProgressUpdate ()" is executed in the UI thread.

--The value passed to the argument of publishProgress () is passed to the argument of onProgressUpdate () as it is. --The argument type is specified in the second part of AsyucTask generics.

private class PostAccess extends AsyucTask< String, String, String > {   
                             ...
  public String doInBackground(String ... parent) {
                         ...
    publishProgress(String);
  }

  public void onProgressUpdate(String ... values) {
    super.onProgressUpdate(values);//Write as a promise
  }
}

Sample code to POST to the server

public class PostActivity extends AppCompatActivity {

    private static final String ACCESS_URL = "http://xxx.xxx.xx/xx/~~~.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);
    }

    public void sendButtonClick(View view) {
        EditText etName = findViewById(R.id.etName);
        EditText etComment = findViewById(R.id.etComment);
        TextView tvProcess = findViewById(R.id.tvProcess);
        TextView tvResult = findViewById(R.id.tvResult);

        tvProcess.setText("");
        tvResult.setText("");

        String name = etName.getText().toString();
        String comment = etComment.getText().toString();

        PostAccess access = new PostAccess(tvProcess, tvResult);
        access.execute(ACCESS_URL, name, comment);
    }

    private class PostAccess extends AsyncTask<String, String, String> {
        private static final String DEBUG_TAG = "PostAccess";
        private TextView _tvProcess;
        private TextView _tvResult;
        private boolean _success = false;

        public PostAccess(TextView tvProcess, TextView tvResult) {
            _tvProcess = tvProcess;
            _tvResult = tvResult;
        }

        @Override
        public String doInBackground(String... params) {
            String urlStr = params[0];
            String name = params[1];
            String comment = params[2];

            String postData = "name= " + name + "&comment=" + comment;
            HttpURLConnection con = null;
            InputStream is = null;
            String result = "";

            try {
                publishProgress(getString(R.string.msg_send_before));
                URL url = new URL(urlStr);
                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                con.setConnectTimeout(5000);
                con.setReadTimeout(5000);
                con.setDoOutput(true);
                OutputStream os = con.getOutputStream();
                os.write(postData.getBytes());
                os.flush();
                os.close();
                int status = con.getResponseCode();
                if (status != 200) {
                    throw new IOException("Status code: " + status);
                }
                publishProgress(getString(R.string.msg_send_after));
                is = con.getInputStream();

                result = is2String(is);
                _success = true;
            }
            catch(SocketTimeoutException ex) {
                publishProgress(getString(R.string.msg_err_timeout));
                Log.e(DEBUG_TAG, "time out", ex);
            }
            catch(MalformedURLException ex) {
                publishProgress(getString(R.string.msg_err_send));
                Log.e(DEBUG_TAG, "URL conversion failure", ex);
            }
            catch(IOException ex) {
                publishProgress(getString(R.string.msg_err_send));
                Log.e(DEBUG_TAG, "Communication failure", ex);
            }
            finally {
                if (con != null) {
                    con.disconnect();
                }
                try {
                    if (is != null) {
                        is.close();
                    }
                }
                catch (IOException ex) {
                    publishProgress(getString(R.string.msg_err_parse));
                    Log.e(DEBUG_TAG, "InputStream analysis failed", ex);
                }
            }
            return result;
        }

        @Override
        public void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
            String message = _tvProcess.getText().toString();
            if (!message.equals("")) {
                message += "\n";
            }
            message += values[0];
            _tvProcess.setText(message);
        }

        @Override
        public void onPostExecute(String result) {
            if (_success) {
                String name = "";
                String comment = "";
                onProgressUpdate(getString(R.string.msg_parse_before));
                try {
                    JSONObject rootJson = new JSONObject(result);
                    name = rootJson.getString("name");
                    comment = rootJson.getString("comment");
                }
                catch (JSONException ex) {
                    onProgressUpdate(getString(R.string.msg_err_parse));
                    Log.e(DEBUG_TAG, "JSON parsing failed", ex);
                }
                onProgressUpdate(getString(R.string.msg_parse_after));

                String message = getString(R.string.dlg_msg_name) + name + "\n" + getString(R.string.dlg_msg_comment) + comment;
                _tvResult.setText(message);
            }
        }

        private String is2String(InputStream is) throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer sb = new StringBuffer();
            char[] b = new char[1024];
            int line;
            while(0 <= (line = reader.read(b))) {
                sb.append(b, 0, line);
            }
            return sb.toString();
        }
    }
}

that's all. If you have any suggestions such as something wrong, please contact us. Thank you for reading to the end.

Recommended Posts

Android development-WEB access (POST) Try to communicate with the outside and send data. ~
Android development-WEB access (GET) Try to get data by communicating with the outside. ~
Going back to the beginning and getting started with Java ① Data types and access modifiers
Run logstash with Docker and try uploading data to Elastic Cloud
Read the data of Shizuoka point cloud DB with Java and try to detect the tree height.
How to change the maximum and maximum number of POST data in Spark
Send and process form data to Servlet with FormData object and Commons File Upload
Android app: Try to summarize events and listeners
Try to summarize the common layout with rails
NLP4J [005-1] Try Twitter analysis with Twitter4J and NLP4J (data collection)
Communicate from the outside to the container launched by docker-compose
Access Web API on Android with Get and process Json (Java for the time being)
How to take a screenshot with the Android Studio emulator
[MT] Specify the article category from Android with Data API
Android app to select and display images from the gallery
Create API to send and receive Json data in Spring
[MT] Specify the article category from Android with Data API
I want to distinct the duplicated data with has_many through
Send the accelerometer value from Android to PC via UDP
Technical causes and countermeasures for the points I was addicted to with the first Android app & Kotlin