관리 메뉴

moozi

android에서 get,post로 데이터 넘기기 본문

안드로이드개발강좌

android에서 get,post로 데이터 넘기기

moozi 2017. 9. 29. 13:54

package com.naver.jspconn04;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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 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 {
    LinearLayout linearLayout1;
    EditText et1;
    Button btn1;
    DownloadWebpageTask myTask;

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

        //LinearLayout찾기
        linearLayout1=(LinearLayout)findViewById(R.id.linearLayout);

        //EditText찾기
        et1=(EditText)findViewById(R.id.editText);

        btn1=(Button)findViewById(R.id.button);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //JSP연동.json파싱해서 ArrayList에 추가

                //get방식일 때 url
                String url="http://10.0.2.2:8181/AndroidConn01/CustomerSearch.jsp?search="+et1.getText().toString();
                //post방식일 때 url
//                String url="http://10.0.2.2:8181/AndroidConn01/CustomerSearch.jsp";
                //AsyncTask실행
                myTask=new DownloadWebpageTask();
                myTask.execute(url);
            }
        });


    }


    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("search", et1.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) {
            //listView초기화
            linearLayout1.removeAllViews();

            try {

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

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

                    json = jArr.getJSONObject(i);

                    final String id    = json.getString("id");
                    String name    = json.getString("name");
                    String address = json.getString("address");

                    LinearLayout linear = new LinearLayout(getApplicationContext());
                    linear.setOrientation(LinearLayout.HORIZONTAL);

                    TextView textView = new TextView(getApplicationContext());
                    textView.setWidth(150);
                    textView.setText(id);
                    textView.setId(i);
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(getApplicationContext(),id,Toast.LENGTH_LONG).show();
                        }
                    });
                    linear.addView(textView);


                    TextView textView1 = new TextView(getApplicationContext());
                    textView1.setWidth(150);
                    textView1.setText(name);
                    linear.addView(textView1);

                    TextView textView2 = new TextView(getApplicationContext());
                    textView2.setWidth(500);
                    textView2.setText(address);
                    linear.addView(textView2);

                    linearLayout1.addView(linear);

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

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

안드로이드 로그인  (0) 2017.09.29
login.jsp  (0) 2017.09.29
CustomerSearch.jsp  (0) 2017.09.29
json데이터 java코드로 뷰에 출력하기  (0) 2017.09.29
json데이터 listview에 출력하기  (0) 2017.09.29
Comments