관리 메뉴

moozi

안드로이드 로그인 본문

안드로이드개발강좌

안드로이드 로그인

moozi 2017. 9. 29. 15:21

package com.naver.member;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Properties;

public class MainActivity extends AppCompatActivity {
    EditText et1, et2;
    TextView tv1;
    Button btn1,btn2;
    DownloadWebpageTask myTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et1=(EditText)findViewById(R.id.editText); //id
        et2=(EditText)findViewById(R.id.editText2); //pw
        btn1=(Button)findViewById(R.id.button); //로그인버튼
        btn2=(Button)findViewById(R.id.button2);//Join버튼
        tv1=(TextView)findViewById(R.id.textView4);//결과출력 TextView

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //JSP연동.json파싱해서 ArrayList에 추가
                //post방식일 때 url
                String url="http://10.0.2.2:8181/AndroidConn01/Login.jsp";
                //AsyncTask실행
                myTask=new DownloadWebpageTask();
                myTask.execute(url);
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,JoinActivity.class);
                startActivity(intent);
            }
        });

    }

    //Parameter를 인코딩해서 문자열로 리턴
    public static String encodeString(Properties params) {
        StringBuffer sb = new StringBuffer(256);
        Enumeration names = params.propertyNames();

        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = params.getProperty(name);
            try{
                sb.append(URLEncoder.encode(name) + "=" + URLEncoder.encode(value,"utf-8") );
            }catch(Exception e){
                e.printStackTrace();
            }

            if (names.hasMoreElements()) sb.append("&");
        }
        return sb.toString();
    }

    private class DownloadWebpageTask extends AsyncTask<String,Void,String> {

        //주요 내용 실행
        @Override
        protected String doInBackground(String... urls) {
            try {
                return (String)downloadUrl((String)urls[0]);
            } catch (IOException e) {
                return "다운로드 실패";
            }
        }

        private String downloadUrl(String myurl) throws IOException {

            HttpURLConnection conn = null;
            try {

                URL url = new URL(myurl);
                conn = (HttpURLConnection) url.openConnection();

                /* post방식으로 처리 시작 ==========================*/
                conn.setDoInput(true);
                conn.setDoOutput(true);

                conn.setUseCaches(false);

                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

                DataOutputStream out = null;

                out = new DataOutputStream(conn.getOutputStream());
                Properties prop = new Properties();
                prop.setProperty("id", et1.getText().toString());
                prop.setProperty("pw", JoinActivity.getHash(et2.getText().toString()));
                String encodedString = encodeString(prop);

                out.writeBytes(encodedString);
                out.flush();
                /* post방식으로 처리 끝 ===============================*/


                BufferedInputStream buf = new BufferedInputStream(conn.getInputStream());
                BufferedReader bufreader = new BufferedReader(new InputStreamReader(buf, "utf-8"));
                String line = null;
                String page = "";
                while((line = bufreader.readLine()) != null) {
                    page += line;
                }

                return page;
            } finally {
                conn.disconnect();
            }
        }

        //ui변경 작업 실행
        @Override
        protected void onPostExecute(String result) {


            try {

                JSONObject json = new JSONObject(result);
                JSONArray jArr = json.getJSONArray("result");

                for (int i=0; i<jArr.length(); i++) {

                    json = jArr.getJSONObject(i);

                    final String msg    = json.getString("msg");
                    Log.d("디버깅 msg : ",msg);
                    if(msg.equals("ok")){
                        tv1.setText("로그인 성공");
                    }else{
                        tv1.setText("로그인 실패");
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

'안드로이드개발강좌' 카테고리의 다른 글

datepicker 년월만 표시하기  (0) 2017.11.21
jsoup사용하기  (0) 2017.10.10
login.jsp  (0) 2017.09.29
android에서 get,post로 데이터 넘기기  (0) 2017.09.29
CustomerSearch.jsp  (0) 2017.09.29
Comments