'Android/HttpClient example'에 해당되는 글 1건

  1. 2010/10/04 Android HttpClient example (5)

HttpClient example

안드로이드에서는 2가지 방식의 네트워크 연결방식을 제공한다.

1. 기존 자바에 포함되어 있는 자바 전통적인 방식

2. 기존 자바에는 없고 안드로이드에는 포함된 Apache 라이브러리를 사용하는 방식


다음은 Apache 라이브러리를 이용한 방식으로 웹서버에 접속하여 XML문서를 수신하는 안드로이드 프로그램의 예이다.


AndroidMenifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.ojtit.android.test.http"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".HttpConActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="7" />
 <uses-permission android:name="android.permission.INTERNET"/>

</manifest>




main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:id="@+id/text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>




HttpConActivity.java

package com.ojtit.android.test.http;
import java.io.*;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

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

public class HttpConActivity extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     TextView text =   (TextView)this.findViewById(R.id.text);
     try{
     //text.setText(getStringFromUrl("http://naver.com"));
     text.setText(getStringFromUrl(http://172.16.70.44/WebApp/index.jsp);
     }catch(Exception e){
      e.printStackTrace();
     }
     /* 웹서버에서 이미지를 수신하여 이미지뷰에 출력한다 */
     ImageView img = (ImageView)findViewById(R.id.img);
     Bitmap bitmap =
         DownloadImage("http://www.android.com/images/developers.gif");
     img = (ImageView) findViewById(R.id.img);
     img.setImageBitmap(bitmap);

     /* 웹서버에서 XML문서를 다운로드하여 Toast에 출력한다 */
     DownloadXML("http://172.16.70.44/WebApp/index.jsp");
 }
   
    public static InputStream getInputStreamFromUrl(String url){
       InputStream contentStream = null;
   
       try{
         HttpClient httpclient = new DefaultHttpClient();
         HttpResponse response = httpclient.execute(new HttpGet(url));
         contentStream = response.getEntity().getContent();
       } catch(Exception e){
          e.printStackTrace();
       }
       return contentStream;
    }
   
    public static String getStringFromUrl(String url) throws UnsupportedEncodingException{
    BufferedReader br = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url),"euc-kr"));
     
    StringBuffer sb = new StringBuffer();
   
    try{
     String line = null;
    
     while ((line = br.readLine())!=null){
      sb.append(line);
     }
    }catch (IOException e){
     e.printStackTrace();
    }
    return sb.toString();
 }

    private Bitmap DownloadImage(String URL)
    {       
        Bitmap bitmap = null;
        InputStream in = null;       
        try {
            in = getInputStreamFromUrl(URL);
            bitmap = BitmapFactory.decodeStream(in);
            /* 위에서 리턴된 bitmap은 ImageView에 출력할 수 있다 */
            in.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return bitmap;               
    }
   
    private void DownloadXML(String URL)
    {
        InputStream in = null;
        try {
            in = getInputStreamFromUrl(URL);
            Document doc = null;
            DocumentBuilderFactory dbf =
                DocumentBuilderFactory.newInstance();
            DocumentBuilder db;
           
            try {
                db = dbf.newDocumentBuilder();
                doc = db.parse(in);
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            }       
           
            doc.getDocumentElement().normalize(); 
            
            NodeList itemNodes = doc.getElementsByTagName("student");
           
            String strName = null;
            for (int i = 0; i < itemNodes.getLength(); i++) {
                Node itemNode = itemNodes.item(i);
                if (itemNode.getNodeType() == Node.ELEMENT_NODE)
                {            
                    Element itemElement = (Element) itemNode;
                    
                    NodeList nameNodes =  itemElement.getElementsByTagName("name");
                    
                    Element nameElement = (Element) nameNodes.item(0);
                    
                    Node node = nameElement.getFirstChild();
                    strName = node.getNodeValue();

                    Toast.makeText(getBaseContext(),strName,
                        Toast.LENGTH_SHORT).show();
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();           
        }
    }

}




http://172.16.70.44/WebApp/index.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>환영합니다</title>
</head>
<body>
<%="index.jsp에 접속되었습니다" %>
</body>
</html>

사용자 삽입 이미지


JSP에서 Android단말기에 XML 포맷으로 응답하는 경우

<%@ page language="java" contentType="text/xml;charset=utf-8" %>
<students>
 <student>
  <name>홍길동</name>
  <num>100</num>
  <phone>234-6534-2345</phone>
 </student>
 <student>
  <name>박지성</name>
  <num>200</num>
  <phone>324-7546-8678</phone>
 </student>
</students>



Posted by cwisky