แจกตัวอย่าง Android studio 3.3.1 Api 28 (oreo) sendHttp sendHttps AsyncTask setTimeout()
เพื่อจะเป็นประโยชน์สำหรับคนหัด เชื่อมต่อกับ web server
เริ่มต้น ก็ Manifest.xml config สำหรับ internet
<uses-permission android:name="android.permission.INTERNET" />
Code (XML)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.e.chaidhanan">
<uses-permission android:name="android.permission.INTERNET" />
<application
...
...>
...
...
</application>
</manifest>
ตามด้วย เมนู เล็ก ไว้คลิก
Code (XML)
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.e.chaidhanan.MainActivity">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never" />
<item
android:id="@+id/action_getx"
android:orderInCategory="100"
android:title="get_x"
app:showAsAction="never" />
<item
android:id="@+id/action_active"
android:orderInCategory="100"
android:title="Active"
app:showAsAction="never" />
</menu>
class สร้าง parameter สำหรับ post field
Code (Java)
public class MyParam {
public String name;
public String value;
public MyParam(String n, String v){
name = n; value=v;
}
}
Code (Java)
public class paramPostLive {
public Competition com;
public String html;
public paramPostLive(Competition c, String data){
com = c; html = data;
}
}
Class send Http
Code (Java)
public class sendHttp {
private MainActivity main;
private String Program;
private String Option;
private String PostField;
public sendHttp(MainActivity a){
main = a;
}
private String data = "Test DATA";
private String msgLog;
public void active(String... para) {
int ln = para.length;
String lnk = para[0];
Program = para[1];
Option = ln>2 ? para[2] : "";
PostField = ln>3 ? para[3] : "";
new getDataStream().execute(lnk);
}
private void TaskComplete(Boolean isComplete){
if(isComplete){
main.callback(Program, "ok", data, Option);
}else{
main.callback(Program, "er", msgLog, Option);
}
}
private class getDataStream extends AsyncTask<String, Void, String> {
private HttpURLConnection con;
Boolean readSuccess;
@Override
protected String doInBackground(String... urls){
try {
URL request_url = new URL(urls[0]);
con = (HttpURLConnection) request_url.openConnection();
if(PostField.length()>0){
con.setRequestMethod("POST");
}else {
con.setRequestMethod("GET");
}
con.setReadTimeout(95 * 1000);
con.setConnectTimeout(95 * 1000);
con.setDoInput(true);
con.setRequestProperty("Accept", "application/text");
con.setRequestProperty("X-Environment", "android");
if(PostField.length()>0){
OutputStream out = null;
out = new BufferedOutputStream(con.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(PostField);
writer.flush();
writer.close();
out.close();
}
con.connect();
convertStream2String();
return readSuccess? "1" : "0";
} catch (IOException e) {
data += e.getMessage();
e.printStackTrace();
con.disconnect(); con = null;
} return "0";
}
@Override
protected void onPostExecute(String finish) {
TaskComplete(finish.equals("1"));
}
private void convertStream2String(){
BufferedReader br = null;
try {
int code = con.getResponseCode();
readSuccess=(code == 200);
msgLog = "HTTP error code" + code;
if (readSuccess) {
InputStream inputStream = con.getInputStream();
if (inputStream != null)
br = new BufferedReader(new InputStreamReader(inputStream));
} else {
InputStream inputStream = con.getErrorStream();
if (inputStream != null)
br = new BufferedReader(new InputStreamReader(inputStream));
}
String output;
while ((output = br.readLine()) != null) {
if(readSuccess) {
data += output;
}else{
msgLog += output;
}
}
br.close(); con.disconnect();
}catch(IOException e){
msgLog += "error "+e.getMessage();
}
}
}
}
Class send Https
Code (Java)
public class sendHttps {
private MainActivity main;
private String Program;
private String Option;
private String PostField;
public sendHttps(MainActivity a){
main = a;
}
private String data = "Test DATA";
private String msgLog;
public void active(String... para) {
int ln = para.length;
String lnk = para[0];
Program = para[1];
Option = ln>2 ? para[2] : "";
PostField = ln>3 ? para[3] : "";
new getDataStream().execute(lnk);
}
private void TaskComplete(Boolean isComplete){
if(isComplete){
main.callback(Program, "ok", data, Option);
}else{
main.callback(Program, "er", msgLog, Option);
}
}
private class getDataStream extends AsyncTask<String, Void, String> {
private HttpsURLConnection con;
Boolean readSuccess;
@Override
protected String doInBackground(String... urls){
try {
URL request_url = new URL(urls[0]);
con = (HttpsURLConnection) request_url.openConnection();
if(PostField.length()>0){
con.setRequestMethod("POST");
}else {
con.setRequestMethod("GET");
}
con.setReadTimeout(95 * 1000);
con.setConnectTimeout(95 * 1000);
con.setDoInput(true);
con.setRequestProperty("Accept", "application/text");
con.setRequestProperty("X-Environment", "android");
con.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
con.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
if(PostField.length()>0){
OutputStream out = null;
out = new BufferedOutputStream(con.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(PostField);
writer.flush();
writer.close();
out.close();
}
con.connect();
convertStream2String();
return readSuccess? "1" : "0";
} catch (IOException e) {
data += e.getMessage();
e.printStackTrace();
con.disconnect(); con = null;
} return "0";
}
@Override
protected void onPostExecute(String finish) {
TaskComplete(finish.equals("1"));
}
private void convertStream2String(){
BufferedReader br = null;
try {
int code = con.getResponseCode();
readSuccess=(code == 200);
msgLog = "HTTP error code" + code;
if (readSuccess) {
InputStream inputStream = con.getInputStream();
if (inputStream != null)
br = new BufferedReader(new InputStreamReader(inputStream));
} else {
InputStream inputStream = con.getErrorStream();
if (inputStream != null)
br = new BufferedReader(new InputStreamReader(inputStream));
}
String output;
while ((output = br.readLine()) != null) {
if(readSuccess) {
data += output;
}else{
msgLog += output;
}
}
br.close(); con.disconnect();
}catch(IOException e){
msgLog += "error "+e.getMessage();
}
}
}
}
มาถีง java ตัวหลัก
MainActivity.java
Code (Java)
public class MainActivity extends AppCompatActivity {
Boolean forActive = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
html = findViewById(R.id.html);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case R.id.action_settings:
// Setting Menu
return true;
case R.id.action_getx:
setTimeout(("GetX"),(1));
return true;
case R.id.action_active:
forActive=!forActive;
String tt = forActive ? "Stop get Asianbookie" : "Start get Asianbookie";
item.setTitle(tt);
return true;
default:
}
return super.onOptionsItemSelected(item);
}
// -------------------------------------------------------
// Tool setTimeout()
public void setTimeout(final String name, int sec){
Runnable myRunnable = new Runnable(){
public void run(){
timeoutRun(name);
}
};
new android.os.Handler().postDelayed( myRunnable, sec);
}
public void timeoutRun(String... para){
switch(para[0]){
case "GetX":
new sendHttp(this).execute("","GetY","","");
break;
case "GetY":
// use String[] callPara
break;
default:
}
}
// -------------------------------------------------------
// callback from AsynTask
private String[] callPara;
public void callback(String... str) {
callPara = str;
setTimeout(str[0], 1);
}
// -------------------------------------------------------
// JSON tool:: JSON String to JSON
public JSONObject cv2js(String str){
JSONObject rs;
try {
rs = new JSONObject(str);
}catch(Exception e){
rs = cv2js("{}");
}
return rs;
}
// class to JSON String
public String toJSON(paramPostLive r){
JSONObject jsonObject= new JSONObject();
try {
jsonObject.put("com", r.com);
jsonObject.put("html", r.html);
return jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
return "";
}
}
// -------------------------------------------------------
// Parameter for post field
public String setParam(List<MyParam> params){
try{
return getQuery(params);
}catch(UnsupportedEncodingException e){
return "";
}
}
// convert Parameter to string
public String getQuery(List<MyParam> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (MyParam pair : params)
{
if (first) first = false;
else result.append("&");
result.append(URLEncoder.encode(pair.name, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.value, "UTF-8"));
}
return result.toString();
}
}
เอาคลาสใช้งานไปก่อนนะครับ ไว้ว่างๆ จะเข้ามาเพิ่มเติม วิธีใช้งาน
พอดีเขียนใช้เอง เลยเอามาแจกTag : Java, Android, JAVA
Date :
2019-02-26 11:30:51
By :
Chaidhanan
View :
2801
Reply :
1
เยี่ยมเลยครับ
Date :
2019-02-26 11:59:11
By :
mr.win
Load balance : Server 01