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.
--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. ~.
String postData =“Request parameter 1= ” +Value 1+ “ &Request parameter 2= ” +Value 2
con.setRequestMethod(“POST”)
con.setDoOutput(true)
OutputStream os = con.getOutputStream()
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
}
}
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