httpURLConnection을 이용한 안드로이드,php,mysql 서버 연동
오늘은 따로 설명없이 httpURLConnection과 저번 포스팅에 나왔던 AsyncTask를 이용해서
안드로이드 와 서버연동하는 코드를 소개하겠습니다. 간단하게 안드로이드에서 php를 통해서, 서버에 넣는 코드를 보여드리겠습니다.
먼저 php코드입니다.
그다음에는 안드로이드 코드입니다.
마지막으로 mysql code 및 설명입니다.
좋은 하루 되세용
안드로이드 와 서버연동하는 코드를 소개하겠습니다. 간단하게 안드로이드에서 php를 통해서, 서버에 넣는 코드를 보여드리겠습니다.
먼저 php코드입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
<?php
$servername = "xxx.xxx.xxx.xxx";
$username = "rabbit";
$password = "password";
$dbname = "blog";
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($conn,"utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$tmsg = $_POST['tmsg']; //Async에 있는 String과 같이 매치해서 보시면 좋습니다.
$tmsg2 = $_POST['tmsg2'];//
// echo $tmsg.$tmsg2;
$sql = "insert into blog_test(value1, value2) values('$tmsg','$tmsg2')";//아이템삽입!
$result = mysqli_query($conn,$sql);//쿼리 !
if($result){ //결과에 따라서 메세지 에코~
echo 'success';
}
else{
echo 'failure';
}
$conn->close(); //connection 종료시킨다.
?>
| cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
|
public class URLConnection_http extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_urlconnection);
textView=(TextView) findViewById(R.id.myid);
Async_Prepare();
}
public void Async_Prepare(){
Async_test async_test =new Async_test();
async_test.execute("hello","rabbit");//요렇게 스트링값들을 넘겨줍시다. 저번시간에 포스팅을 보시면 Data Type을 어떻게 할지 결정 할 수 있습니다. 힘내봅시다.
}
class Async_test extends AsyncTask<String,Void,String>{
ProgressDialog dialog;
int cnt=0;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog=ProgressDialog.show(URLConnection.this,"이것은 URLConnection Test입니다...",null,true,true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
dialog.dismiss();//Dialog를 dissmiss합니다.
textView.setText("I got Msg from Server! : "+s);// TextView에 보여줍니다.
// Toast.makeText(getApplicationContext(),"i got a msg from server :"+s,Toast.LENGTH_LONG).show();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
Log.d("onProgress update",""+cnt++);
}
@Override
protected String doInBackground(String... params) {
HttpURLConnection httpURLConnection = null;
try{
String tmsg = params[0];
String tmsg2 = params[1];
String data = URLEncoder.encode("tmsg","UTF-8")+"="+URLEncoder.encode(tmsg,"UTF-8");// UTF-8로 설정 실제로 string 상으로 봤을땐, tmsg="String" 요런식으로 설정 된다.
data+= "&"+URLEncoder.encode("tmsg2","UTF-8")+"="+URLEncoder.encode(tmsg2,"UTF-8");
// String data2 = "tmsg="+testMsg+"&tmsg2="+testMsg2;
String link = "http://xxx.xxx.xxx.xxx/"+"test.php";// 요청하는 url 설정 ex)192.168.0.1/httpOnlineTest.php
URL url = new URL(link);
httpURLConnection = (HttpURLConnection) url.openConnection();//httpURLConnection은 url.openconnection을 통해서 만 생성 가능 직접생성은 불가능하다.
httpURLConnection.setRequestMethod("POST");//post방식으로 설정
httpURLConnection.setDoInput(true);// server와의 통신에서 입력 가능한 상태로 만든다.
httpURLConnection.setDoOutput(true);//server와의 통신에서 출력 가능한 상태로 ㅏㄴ든다.
// httpURLConnection.setConnectTimeout(30);// 타임 아웃 설정 default는 무제한 unlimit이다.
OutputStreamWriter wr = new OutputStreamWriter(httpURLConnection.getOutputStream());//서버로 뿅 쏴줄라구용
wr.write(data);//아까 String값을 쓱삭쓱삭 넣어서 보내주고!
wr.flush();//flush!
BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"UTF-8"));//자 이제 받아옵시다.
StringBuilder sb = new StringBuilder();// String 값을 이제 스슥스슥 넣을 껍니다.
String line;
while ((line= reader.readLine())!=null){
sb.append(line);//
}
httpURLConnection.disconnect();//이거 꼭해주세요. 보통은 별일 없는데, 특정상황에서 문제가 생기는 경우가 있다고 합니다.
return sb.toString();//자 이렇게 리턴이되면 이제 post로 가겠습니다.
}catch (Exception e){
httpURLConnection.disconnect();
return new String ("Exception Occure"+e.getMessage());
}//try catch end
}//doInbackground end
}//asynctask end
}
| cs |
마지막으로 mysql code 및 설명입니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| blog |
.
.
.
.
.
.
요로코롬 있을꺼에요....
mysql> use blog
Database changed
요렇게 해서
table을 만들어 봅시다.
mysql> use blog
Database changed
mysql> create table blog_test(
-> a_id INT PRIMARY KEY AUTO_INCREMENT,
-> value1 VARCHAR(50) NOT NULL,
-> value2 VARCHAR(20) NOT NULL
-> );
Query OK, 0 rows affected (0.16 sec)
mysql> show tables;
+----------------+
| Tables_in_blog |
+----------------+
| blog_test |
+----------------+
1 row in set (0.02 sec)
mysql> desc blog_test;
+--------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+----------------+
| a_id | int(11) | NO | PRI | NULL | auto_increment |
| value1 | varchar(50) | NO | | NULL | |
| value2 | varchar(20) | NO | | NULL | |
+--------+-------------+------+-----+---------+----------------+
3 rows in set (0.02 sec)
이렇게 되면 성공이에용
| cs |
좋은 하루 되세용
댓글
댓글 쓰기