1. 在Manifest.xml裡插入
<uses-permission android:name=
"android.permission.INTERNET"/
>
2.創建一個新的Activity,GetServer.java
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
| package com.example.photothrow1; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class GetServer { public String stringQuery(String url){ try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse response = httpClient.execute(httpPost); HttpEntity httpEntity = response.getEntity(); if (httpEntity!= null ) return EntityUtils.toString(httpEntity); else return "no string." ; } catch (Exception e) { // TODO: handle exception return "Network Problem." ; } } } |
3. 在MainActivity(也可以是別的)加入一個method,可以在OnCreat呼叫這個method就好
1
2
3
4
5
| public void getServerMsg(){ GetServer server = new GetServer(); server_msg.setText(msg); } |
4. 在你的server新增php(ex test.php)
1
2
3
| <?php echo "Hi, I'm server." ; ?> |
測試結果: