관리 메뉴

moozi

jspconn01 본문

안드로이드개발강좌

jspconn01

moozi 2017. 9. 29. 10:42

package com.example.pjs.jsontestas;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;


import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView tv;

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

        tv = (TextView) findViewById(R.id.data);


      String strUrl = "http://10.0.2.2:8181/Android01/Customers.jsp";

        new DownloadWebpageTask().execute(strUrl);
    }

    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 "다운로드 실패";
            }
        }

        protected void onPostExecute(String result) {
            tv.append(result + "\n");
            tv.append("========== 파싱 결과 ==========\n");
            try {

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

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

                    json = jArr.getJSONObject(i);

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

                    tv.append(name + "\n");
                    tv.append(address + "\n");
                }
            } catch (Exception e) {
                tv.setText(e.getMessage());
            }
        }

        private String downloadUrl(String myurl) throws IOException {

            HttpURLConnection conn = null;
            try {
                URL url = new URL(myurl);
                conn = (HttpURLConnection) url.openConnection();
                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();
            }
        }
    }
}

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

json데이터 listview에 출력하기  (0) 2017.09.29
customerdb.jsp  (0) 2017.09.29
jspconn01  (0) 2017.09.29
customers.jsp  (0) 2017.09.29
android xml 파싱  (0) 2017.09.27
BroadCast Action List  (0) 2017.09.27
0 Comments
댓글쓰기 폼