티스토리 뷰

728x90

안드로이드 및 자바에서 DB에 접속하여 데이터를
입력 및 수정 그리고 받아오기 위한 php 파일에 접속하는 클레스입니다.

예제1 : 데이터 입력 - http://twinw.tistory.com/29
예제2 : 데이터 출력 - 미정
예제3 : 데이터 수정 - 미정

1. NetworkUtil.class

1
2
3
4
5
6
7
8
9
10
11
import android.annotation.SuppressLint;
import android.os.StrictMode;
public class NetworkUtil {
   @SuppressLint("NewApi")
   static public void setNetworkPolicy() {
       if (android.os.Build.VERSION.SDK_INT > 9) {
           StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
           StrictMode.setThreadPolicy(policy);
       }
   }
}


2. PHPRequest.class

PHPRequest.class안의 함수 phptest를 변형하여 변수에 따라 추가하시면 됩니다.

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
import android.util.Log;
 
public class PHPRequest {
    private URL url;
     
    public PHPRequest(String url) throws MalformedURLException { this.url = new URL(url); }
     
    private String readStream(InputStream in) throws IOException {
        StringBuilder jsonHtml = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
        String line = null;
         
        while((line = reader.readLine()) != null)
            jsonHtml.append(line);
         
        reader.close();
        return jsonHtml.toString();
    }
     
    public String PhPtest(final String data1, final String data2,final String data3) {
        try {
            String postData = "Data1=" + data1 + "&" + "Data2=" + data2 + "&" + "Data3=" + data3;
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(postData.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();          
            String result = readStream(conn.getInputStream());
            conn.disconnect();
            return result;
        }
        catch (Exception e) {
            Log.i("PHPRequest", "request was failed.");
            return null;
        }
    }
    }

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
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
글 보관함